详解feign调用session丢失解决方案

 更新时间:2019年02月18日 15:32:35   作者:zl1zl2zl3  
这篇文章主要介绍了详解feign调用session丢失解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

最近在做项目的时候发现,微服务使用feign相互之间调用时,存在session丢失的问题。例如,使用Feign调用某个远程API,这个远程API需要传递一个鉴权信息,我们可以把cookie里面的session信息放到Header里面,这个Header是动态的,跟你的HttpRequest相关,我们选择编写一个拦截器来实现Header的传递,也就是需要实现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); 
    } 
   } 
  } 
 
 } 
 
} 

经过测试,上面的解决方案可以正常的使用; 

但是,当引入Hystrix熔断策略时,出现了一个新的问题:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

此时requestAttributes会返回null,从而无法传递session信息,最终发现RequestContextHolder.getRequestAttributes(),该方法是从ThreadLocal变量里面取得对应信息的,这就找到问题原因了,是由于Hystrix熔断机制导致的。 
Hystrix有2个隔离策略:THREAD以及SEMAPHORE,当隔离策略为 THREAD 时,是没办法拿到 ThreadLocal 中的值的。

因此有两种解决方案:

方案一:调整格隔离策略:

hystrix.command.default.execution.isolation.strategy: SEMAPHORE

这样配置后,Feign可以正常工作。

但该方案不是特别好。原因是Hystrix官方强烈建议使用THREAD作为隔离策略! 可以参考官方文档说明。

方案二:自定义策略

记得之前在研究zipkin日志追踪的时候,看到过Sleuth有自己的熔断机制,用来在thread之间传递Trace信息,Sleuth是可以拿到自己上下文信息的,查看源码找到了 
org.springframework.cloud.sleuth.instrument.hystrix.SleuthHystrixConcurrencyStrategy 
这个类,查看SleuthHystrixConcurrencyStrategy的源码,继承了HystrixConcurrencyStrategy,用来实现了自己的并发策略。

/**
 * Abstract class for defining different behavior or implementations for concurrency related aspects of the system with default implementations.
 * <p>
 * For example, every {@link Callable} executed by {@link HystrixCommand} will call {@link #wrapCallable(Callable)} to give a chance for custom implementations to decorate the {@link Callable} with
 * additional behavior.
 * <p>
 * When you implement a concrete {@link HystrixConcurrencyStrategy}, you should make the strategy idempotent w.r.t ThreadLocals.
 * Since the usage of threads by Hystrix is internal, Hystrix does not attempt to apply the strategy in an idempotent way.
 * Instead, you should write your strategy to work idempotently. See https://github.com/Netflix/Hystrix/issues/351 for a more detailed discussion.
 * <p>
 * See {@link HystrixPlugins} or the Hystrix GitHub Wiki for information on configuring plugins: <a
 * href="https://github.com/Netflix/Hystrix/wiki/Plugins" rel="external nofollow" >https://github.com/Netflix/Hystrix/wiki/Plugins</a>.
 */
public abstract class HystrixConcurrencyStrategy 

搜索发现有好几个地方继承了HystrixConcurrencyStrategy类 

其中就有我们熟悉的Spring Security和刚才提到的Sleuth都是使用了自定义的策略,同时由于Hystrix只允许有一个并发策略,因此为了不影响Spring Security和Sleuth,我们可以参考他们的策略实现自己的策略,大致思路: 

将现有的并发策略作为新并发策略的成员变量; 

在新并发策略中,返回现有并发策略的线程池、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中

 @Bean
 public FeignHystrixConcurrencyStrategy feignHystrixConcurrencyStrategy() {
  return new FeignHystrixConcurrencyStrategy();
 }

至此,结合FeignClientsConfigurationCustom配置feign调用session丢失的问题完美解决。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。 

相关文章

  • 教你用Java Swing实现自助取款机系统

    教你用Java Swing实现自助取款机系统

    今天给大家带来的是关于JAVA的相关知识,文章围绕着如何用Java Swing实现自助取款机系统展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • Java前端开发框架实现的流程和代码示例

    Java前端开发框架实现的流程和代码示例

    我们可以实现一个Java前端开发框架,这个框架包含了初始化、组件渲染、组件更新、事件监听和事件触发等功能,希望这个指南能够对刚入行的小白有所帮助
    2023-10-10
  • Java设计模式之策略模式深入刨析

    Java设计模式之策略模式深入刨析

    策略模式属于Java 23种设计模式中行为模式之一,该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。本文将通过示例详细讲解这一模式,需要的可以参考一下
    2022-05-05
  • ssm mybatis如何配置多个mapper目录

    ssm mybatis如何配置多个mapper目录

    这篇文章主要介绍了ssm mybatis如何配置多个mapper目录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教。
    2022-01-01
  • Spring 容器初始化 register 与 refresh方法

    Spring 容器初始化 register 与 refresh方法

    这篇文章主要介绍了Spring 容器初始化 register 与 refresh方法,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-07-07
  • SpringBoot常用计量与bean属性校验和进制数据转换规则全面分析

    SpringBoot常用计量与bean属性校验和进制数据转换规则全面分析

    这篇文章主要介绍了SpringBoot常用计量、bean属性校验与进制数据转换规则,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2022-10-10
  • Java在PowerPoint幻灯片中创建散点图的方法

    Java在PowerPoint幻灯片中创建散点图的方法

    散点图是通过两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式,这篇文章主要介绍了Java如何在PowerPoint幻灯片中创建散点图,需要的朋友可以参考下
    2023-04-04
  • 排序算法的Java实现全攻略

    排序算法的Java实现全攻略

    这篇文章主要介绍了排序算法的Java实现,包括Collections.sort()的使用以及各种经典算法的Java代码实现方法总结,超级推荐!需要的朋友可以参考下
    2015-08-08
  • SpringBoot security安全认证登录的实现方法

    SpringBoot security安全认证登录的实现方法

    这篇文章主要介绍了SpringBoot security安全认证登录的实现方法,也就是使用默认用户和密码登录的操作方法,本文结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2023-02-02
  • Spring中存对象和取对象的方式详解

    Spring中存对象和取对象的方式详解

    这篇文章主要介绍了Spring中存对象和取对象的方式,Spring中更简单的存对象与取对象的方式是注解,注解实现有两种方式:一在编译的时候,把注解替换成相关代码,并添加到我们原来的代码中,二拦截方法,文中有详细的代码示例供大家参考,需要的朋友可以参考下
    2024-08-08

最新评论