zoukankan      html  css  js  c++  java
  • Springboot feign 传递request信息

    基础实现

    requestInterceptor 实现类中添加信息

    public class NativeFeignConf {
        @Bean
        public RequestInterceptor getRequestInterceptor(){
            return new RequestInterceptor() {
                @Override
                public void apply(RequestTemplate requestTemplate) {
                    ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
                    HttpServletRequest req=servletRequestAttributes.getRequest();
                    Map<String,Collection<String>> headerMap=new HashMap();
                    //获取你需要传递的头信息
                    String myHeaderVal=req.getHeader("myHeader");
                    headerMap.put("myHeader",Arrays.asList(myHeaderVal));
                    //feign请求时,便可携带上该信息
                    requestTempalte.headers(headerMap);
        }
    }
    

    feign加入该config

    @FeignClient(
        value="target-service",
        configuration=NativeFeignConf.class //加入该配置
    )
    public interface MyFeign(){
        ...
    } 
    

    开启 Hystrix 的情况下

    开启hystrix后,feign请求,会运行在hystrix管理的另一线程下。

    所以RequestContextHolder.currentRequestAttributes()无法获取值。

    解决方法:

    创建一个自定义的hystrix 线程策略, 将servletRequestAttributes传入新线程中,并赋给RequestContextHolder:

    public class MyHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy{
        @Override
        public <T> Callable<T> wrapCallable(Callable<T> callable){
            ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return new Callable<T>() {
                @Override
                public T call() throws Exception {
                    try {
                        if (null != servletRequestAttributes) {
                            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
                        }
                        return callable.call();
                    }finally {
                        RequestContextHolder.resetRequestAttributes();
                    }
                }
            };
        }
    }
    

    注册该策略

    @Configuration
    public class HystrixConfig{
        @PostConstruct
        public void init(){
            HystrixPlugins.getInstance().registerConcurrencyStrategy(
                new MyHystrixConcurrencyStrategy()
            )
        }
    }
    

    结束。

  • 相关阅读:
    angular的uiRouter服务学习(2)
    angular的uiRouter服务学习(1)
    angular学习笔记(三十一)-$location(2)
    angular指令中使用ngModelController
    angular中的表单数据自定义验证
    angular-ngSanitize模块-linky过滤器详解
    angular-1.3 之ng-model-options指令
    angular控制器的执行顺序和服务的注入情况
    angular五种服务详解
    .NET CORE EF 框架调用存储过程
  • 原文地址:https://www.cnblogs.com/ztwBlog/p/12302133.html
Copyright © 2011-2022 走看看