feign加入熔断器之后转发不了token等header信息

原创 2019-07-26 11:53 阅读(2372)次

feign加入hystrix熔断器之后转发不了token等header信息,我把熔断注释了,就可以转发。但这不是我想要的答案。

转发代码如下:

@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String token = null;
        String platform = null;
        if(attributes != null) {
        	HttpServletRequest request = attributes.getRequest();
        	token = request.getHeader("token");
        	platform = request.getHeader("p_platform");
        }
        
        //添加token
        requestTemplate.header("token", token);
        requestTemplate.header("p_platform", platform);
    }
}
上面的
ServletRequestAttributes attributes

在熔断中取不到,可能是因为熔断器是异步造成这里取值为null。

后来我修改了下feign与hystrix的配置,问题得到解决,重点是strategy: SEMAPHORE这个配置:

feign:
  hystrix:
    enabled: true
  client:
    config: 
      default:
        requestInterceptors:
          - com.xx.xx.config.FeignConfig
        connectTimeout: 10000
        readTimeout: 60000
        loggerLevel: full

hystrix:
  command:
    default:  #default全局有效,service id指定应用有效
      execution:
        timeout:
          #如果enabled设置为false,则请求超时交给ribbon控制,为true,否则超时作为熔断根据
          enabled: true
        isolation:
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 30000 #断路器超时时间,默认1000ms
ribbon:
  OkToRetryOnAllOperations: false #对所有操作请求都进行重试,默认false
  ReadTimeout: 30000   #负载均衡超时时间,默认值5000
  ConnectTimeout: 30000 #ribbon请求连接的超时时间,默认值2000
  MaxAutoRetries: 0     #对当前实例的重试次数,默认0
  MaxAutoRetriesNextServer: 0 #对切换实例的重试次数,默认1
maven pom.xml:

    <dependency>
    	<groupId>org.springframework.cloud</groupId>
    	<artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
	</dependency>