关于feign调用时,session丢失的解决方案
最近在做公司微服務(wù)項目的時候發(fā)現(xiàn),微服務(wù)使用feign相互之間調(diào)用時,存在session丟失的問題。
例如,使用feign調(diào)用某個遠程API,這個遠程API需要傳遞一個鑒權(quán)信息,我們可以把cookie里面的session信息放到http request Header里面,這個Header是動態(tài)的,跟你的HttpRequest相關(guān),我們選擇編寫一個攔截器來實現(xiàn)Header的傳遞,也就是需要實現(xiàn)RequestInterceptor接口,具體代碼如下:
@Configuration @EnableFeignClients(basePackages = "com.xxx.xxx.client") public class FeignClientsConfigurationCustom implements RequestInterceptor { @Override public void apply(RequestTemplate template) { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes == null) { return; } HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); Enumeration<String> values = request.getHeaders(name); while (values.hasMoreElements()) { String value = values.nextElement(); template.header(name, value); } } } } }
經(jīng)過測試,上面的解決方案可以正常的使用;?
但是,當(dāng)引入Hystrix熔斷策略時,出現(xiàn)了一個新的問題:
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();此時requestAttributes會返回null,從而無法傳遞session信息,最終發(fā)現(xiàn) RequestContextHolder.getRequestAttributes(),該方法是從ThreadLocal變量里面取得對應(yīng)信息的,這就找到問題原因了,是由于Hystrix熔斷機制導(dǎo)致的。?
Hystrix有2個隔離策略:THREAD以及SEMAPHORE,當(dāng)隔離策略為 THREAD 時,是沒辦法拿到 ThreadLocal 中的值的。
因此有兩種解決方案:
方案一:調(diào)整隔離策略:
?
hystrix.command.default.execution.isolation.strategy: SEMAPHORE這樣配置后,feign可以正常工作。
但該方案不是特別好,原因是Hystrix官方強烈建議使用THREAD作為隔離策略! 可以參考官方文檔說明。
方案二:自定義策略
記得之前在研究zipkin日志追蹤的時候,看到過Sleuth有自己的熔斷機制,用來在thread之間傳遞Trace信息,Sleuth是可以拿到自己上下文信息的,于是查看Sleuth的源碼跟蹤到了?
org.springframework.cloud.sleuth.instrument.hystrix.SleuthHystrixConcurrencyStrategy這個類,查看SleuthHystrixConcurrencyStrategy的源碼,此類繼承了抽象類HystrixConcurrencyStrategy,實現(xiàn)了自己的并發(fā)策略。
搜索發(fā)現(xiàn)有好幾個地方繼承了HystrixConcurrencyStrategy類?
其中就有我們熟悉的Spring Security和剛才提到的Sleuth都是使用了自定義的策略,同時由于Hystrix只允許有一個并發(fā)策略,因此為了不影響Spring Security和Sleuth,我們可以參考他們的策略實現(xiàn)自己的策略,大致思路:?
將現(xiàn)有的并發(fā)策略作為新并發(fā)策略的成員變量;?
在新并發(fā)策略中,返回現(xiàn)有并發(fā)策略的線程池、Queue;?
代碼如下:
?
public class FeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy { private static final Logger log = LoggerFactory.getLogger(FeignHystrixConcurrencyStrategy.class); private HystrixConcurrencyStrategy delegate; public FeignHystrixConcurrencyStrategy() { try { this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy(); if (this.delegate instanceof FeignHystrixConcurrencyStrategy) { // Welcome to singleton hell... return; } HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance().getCommandExecutionHook(); HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier(); HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher(); HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy(); this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy); HystrixPlugins.reset(); HystrixPlugins.getInstance().registerConcurrencyStrategy(this); HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook); HystrixPlugins.getInstance().registerEventNotifier(eventNotifier); HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher); HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy); } catch (Exception e) { log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e); } } private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier, HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) { if (log.isDebugEnabled()) { log.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy [" + this.delegate + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher [" + metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]"); log.debug("Registering Sleuth Hystrix Concurrency Strategy."); } } @Override public <T> Callable<T> wrapCallable(Callable<T> callable) { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); return new WrappedCallable<>(callable, requestAttributes); } @Override public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize, HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) { return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties); } @Override public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) { return this.delegate.getBlockingQueue(maxQueueSize); } @Override public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) { return this.delegate.getRequestVariable(rv); } static class WrappedCallable<T> implements Callable<T> { private final Callable<T> target; private final RequestAttributes requestAttributes; public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) { this.target = target; this.requestAttributes = requestAttributes; } @Override public T call() throws Exception { try { RequestContextHolder.setRequestAttributes(requestAttributes); return target.call(); } finally { RequestContextHolder.resetRequestAttributes(); } } } }最后,將這個策略類作為bean配置到feign的配置類FeignClientsConfigurationCustom中
?
@Beanpublic FeignHystrixConcurrencyStrategy feignHystrixConcurrencyStrategy() {return new FeignHystrixConcurrencyStrategy();}至此,結(jié)合FeignClientsConfigurationCustom配置feign調(diào)用session丟失的問題完美解決。
總結(jié)
以上是生活随笔為你收集整理的关于feign调用时,session丢失的解决方案的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在win10下安装自带的linux,并进
- 下一篇: 什么场景应该用 MongoDB ?