本文主要是介绍记一个openFeign使用拦截器RequestInterceptor熔断机制踩坑,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
feign配置如下
@Configuration
public class LoggingConfigure {@Beanpublic Logger.Level config(){return Logger.Level.FULL;}
}
yaml配置如下:
feign:hystrix:enabled: trueclient:config:default:connectTimeout: 100000readTimeout: 100000
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 30000
ribbon:ReadTimeout: 60000ConnectTimeout: 60000
此时feign接口熔断机制为:线程模式,熔断机制正常
配置文件修改为:(使用RequestInterceptor拦截器)
@Configuration
public class FeignConfiguration implements RequestInterceptor {@Overridepublic void apply(RequestTemplate requestTemplate) {ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();Enumeration<String> headerNames = request.getHeaderNames();if (headerNames != null) {while (headerNames.hasMoreElements()) {String name = headerNames.nextElement();String values = request.getHeader(name);requestTemplate.header(name, values);}}}@Beanpublic Logger.Level config(){return Logger.Level.FULL;}
}
导致hystrix熔断机制失效,接口调用异常:
出现该错误原因:
在feign调用之前,我给他开启了一个拦截器 RequestInterceptor实现类
里面有使用到ServletRequestAttributes 获取请求数据
当feign开启熔断模式的时候,feign 调用会失败 (feign: hystrix: enabled: true)
原因:feign 使用的是线程池模式,当开启熔断的时候,feign 所在的服务端不在同一个线程,这是attributes取到的将会是空值
解决方案:
将hystrix熔断方式: 线程模式改为信号量模式
feign:hystrix:enabled: trueclient:config:default:connectTimeout: 100000readTimeout: 100000
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 30000strategy: SEMAPHORE
ribbon:ReadTimeout: 60000ConnectTimeout: 60000
到此问题完美解决;
附带一个文章链接:
文章链接
这篇关于记一个openFeign使用拦截器RequestInterceptor熔断机制踩坑的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!