您的位置:首页 > 编程语言 > Java开发

dubbo的Filter如何读取Spring Boot配置文件值

2018-11-23 10:04 1926 查看

我的dubbo服务端使用的是Spring Boot+Dubbo,本篇文章讲解的是如何在dubbo自带的Filter中得到,我们平时在Spring Boot通过@Autowired注解获取的对象,从而获取到Spring的配置项


dubbo是通过setter方式获取,而通过@Autowired获取Spring中的对象,获得的结果是为null的,本人还通过@ImportResource、@Component、@Service去注解这个Filter的类都是失败的,下面直接上代码:

          通过set  org.springframework.core.env.Environment对象获取属性值

  • [code]import com.alibaba.dubbo.rpc.*;
    import com.alibaba.fastjson.JSONObject;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.core.env.Environment;
    import java.util.List;
    import java.util.Map;
    
    public class CustomTokenFilter implements Filter{
    
    private Logger logger = LoggerFactory.getLogger(CustomTokenFilter.class);
    /**Environment是Spring当前应用的配置对象,可以理解为application.properties本身,大家可以看一下这个对象具体的属性,应该有你想要的值,也可以使用setter其他对象实现你要的逻辑,比如dubbo的接口什么的**/
    private Environment environment;
    
    public Environment getEnvironment() {
    return environment;
    }
    
    public void setEnvironment(Environment environment) {
    this.environment = environment;
    }
    
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation)
    throws RpcException {
    String tokenStr = environment.getProperty("dubbo.token");
    //以下是日志参数,同学们应该要用到,但与本问题无关
    String methodName = invocation.getMethodName();//接口方法名称
    String remoteHost = RpcContext.getContext().getRemoteHost();//请求地址的IP
    String localHost = RpcContext.getContext().getLocalHost();//dubbo服务端IP
    Object[] params = invocation.getArguments();//所有的参数
    Class<?> serviceType = invoker.getInterface();//接口名称
    logger.info("remoteHost=>{},localHost=>{},serviceType=>{},methodName=>{},params=>
    {}",remoteHost,localHost,serviceType,methodName,params);
    return invoker.invoke(invocation);
    
    }
    }

     

其实问题的关键是dubbo的所有的filter都不能通过注解去获取Spring中的对象

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: