当前位置:   article > 正文

SpringCloud 各个微服务之间会话共享以及Feign调用会话共享_feignhystrixconcurrencystrategy

feignhystrixconcurrencystrategy

目录

1、会话共享应用背景

2、SpringCloud各个微服务 (SpringBoot)应用之间会话共享

2.1、启动类或者Redis配置类加入Redis会话共享注解

2.2、配置Redis基本配置内容

3、SpringCloud之中Feign调用微服务实现会话共享


1、会话共享应用背景

     因为以前我们项目之中使用的单一的SpringBoot应用,所有的业务应用、鉴权和登录等操作都是在一个单一的微服务之中进行实现的;由于项目和产品的需要;决定使用现今比较流行的SpringCloud微服务进行重新架构应用。并且把内容分拆为如下几种微服务:独立的网关(Zuul)、注册中心(eureka)、旧的应用服务服务(***Application)、新闻消息服务(news)、人才招聘服务(talent)、论坛问答服务(forum-apis)。但是在调用过程之中所有用户信息存储在会话(Session)之中;如果使用当前比较流行的技术JWT方式传递访问接口权限是不需要会话的。本文将以实际场景下使用会话共享方式来说明如何实现微服务之间的会话共享。

2、SpringCloud各个微服务 (SpringBoot)应用之间会话共享

     实现微服务之间的会话共享、我们系统之中使用的SpringBoot+Redis方式来实现会话共享的;本人分析具体如何实现话共享原理。实际上是用户登录的时候,把回话通过在每个微服务启动类**Application.java上加入会话共享注解(@EnableRedisHttpSession//增加redissession缓存支持)、同时需要在每个微服务(SpringBoot)的配置文件之中配置想用的Redis数据库,实现多个应用同时访问同一个Redis数据库。其底层实现原理是通过把会话存储在Redis之中,然后通过Spring Session实现各个业务应用之间从redis之中获得相同的会话。从而保证的普通的SpringBoot微服务之间会话共享。主要实现和关键代码:

maven引入代码:

  1. <!-- springboot - Redis -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
  7. <dependency>
  8. <groupId>org.springframework.session</groupId>
  9. <artifactId>spring-session-data-redis</artifactId>
  10. </dependency>

2.1、启动类或者Redis配置类加入Redis会话共享注解

  1. 1、在启动类之中加入 EnableRedisHttpSession 注解
  2. @SpringBootApplication
  3. @EnableRedisHttpSession//增加redissession缓存支持
  4. @EnableFeignClients//增加feign支持,引入feign注解,feign扫描路径可以单独指定(basePackages = ),默认是spring的扫描路径
  5. public class ServiceOneApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(ServiceOneApplication.class,args);
  8. }
  9. @Bean
  10. public FeignHystrixConcurrencyStrategy feignHystrixConcurrencyStrategy() {
  11. return new FeignHystrixConcurrencyStrategy();
  12. }
  13. }
  14. 2、在RedisCacheConfig 配置类上配置也一样效果
  15. @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600) // redis托管session
  16. @Configuration
  17. @EnableCaching // 启用缓存
  18. public class RedisCacheConfig extends CachingConfigurerSupport {
  19. }
  20. 以上方案其中任何一种都可以

2.2、配置Redis基本配置内容

  1. spring.session.store-type=none
  2. # redis (redisConfiguration)
  3. spring.cache.type=REDIS
  4. spring.redis.database=11
  5. spring.redis.port=6379
  6. spring.redis.jedis.pool.max-idle=5
  7. spring.redis.jedis.pool.min-idle=0
  8. spring.redis.jedis.pool.max-active=20
  9. spring.redis.jedis.pool.max-wait=2000
  10. spring.redis.timeout=2000
  11. spring.redis.host=127.0.0.1
  12. spring.redis.password=123456

最后会话共享效果如下图所示:

可以看见上面两个截图可以发现不同的应用(端口不同)、其会话是相同的

参考文章:https://blog.csdn.net/zl18310999566/article/details/54290994 https://www.cnblogs.com/yingsong/p/9838198.html

3、SpringCloud之中Feign调用微服务实现会话共享

在实现项目的时候发现,微服务使用feign相互之间调用时,存在session丢失的问题。例如,使用Feign调用某个远程API,这个远程API需要传递一个用户信息,我们可以把cookie里面的session信息放到Header里面,这个Header是动态的,跟你的HttpRequest相关,我们选择编写一个拦截器来实现Header的传递,也就是需要实现RequestInterceptor接口。
 

  1. import feign.RequestInterceptor;
  2. import feign.RequestTemplate;
  3. import org.springframework.cloud.netflix.feign.EnableFeignClients;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.web.context.request.RequestAttributes;
  7. import org.springframework.web.context.request.RequestContextHolder;
  8. import org.springframework.web.context.request.ServletRequestAttributes;
  9. import javax.servlet.http.HttpServletRequest;
  10. import java.util.Enumeration;
  11. /**
  12. * 实现RequestInterceptor,用于设置feign全局请求模板
  13. */
  14. @Configuration
  15. @EnableFeignClients
  16. public class FeignRequestIntercepter implements RequestInterceptor {
  17. @Override
  18. public void apply(RequestTemplate template) {
  19. //通过RequestContextHolder获取本地请求
  20. RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
  21. if (requestAttributes == null) {
  22. return;
  23. }
  24. //获取本地线程绑定的请求对象
  25. HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
  26. System.out.println("=session-id: "+request.getSession().getId());
  27. //给请求模板附加本地线程头部信息,主要是cookie信息
  28. Enumeration<String> headerNames = request.getHeaderNames();
  29. if (headerNames != null) {
  30. while (headerNames.hasMoreElements()) {
  31. String name = headerNames.nextElement();
  32. Enumeration<String> values = request.getHeaders(name);
  33. while (values.hasMoreElements()) {
  34. String value = values.nextElement();
  35. template.header(name, value);
  36. }
  37. }
  38. }
  39. }
  40. }

经过测试,上面的解决方案可以正常的使用; 
但是,当引入Hystrix熔断策略时,出现了一个新的问题;(意味熔断器如果设置false是可以使用)

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

为了完美解决问题建议使用自定义策略

  1. import com.netflix.hystrix.HystrixThreadPoolKey;
  2. import com.netflix.hystrix.HystrixThreadPoolProperties;
  3. import com.netflix.hystrix.strategy.HystrixPlugins;
  4. import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
  5. import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
  6. import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
  7. import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
  8. import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
  9. import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
  10. import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
  11. import com.netflix.hystrix.strategy.properties.HystrixProperty;
  12. import org.apache.commons.logging.Log;
  13. import org.apache.commons.logging.LogFactory;
  14. import org.springframework.web.context.request.RequestAttributes;
  15. import org.springframework.web.context.request.RequestContextHolder;
  16. import java.util.concurrent.BlockingQueue;
  17. import java.util.concurrent.Callable;
  18. import java.util.concurrent.ThreadPoolExecutor;
  19. import java.util.concurrent.TimeUnit;
  20. public class RequestAttributeHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
  21. private static final Log log = LogFactory.getLog(RequestAttributeHystrixConcurrencyStrategy.class);
  22. private HystrixConcurrencyStrategy delegate;
  23. public RequestAttributeHystrixConcurrencyStrategy() {
  24. try {
  25. this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();
  26. if (this.delegate instanceof RequestAttributeHystrixConcurrencyStrategy) {
  27. // Welcome to singleton hell...
  28. return;
  29. }
  30. HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins
  31. .getInstance().getCommandExecutionHook();
  32. HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance()
  33. .getEventNotifier();
  34. HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance()
  35. .getMetricsPublisher();
  36. HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance()
  37. .getPropertiesStrategy();
  38. this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher,
  39. propertiesStrategy);
  40. HystrixPlugins.reset();
  41. HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
  42. HystrixPlugins.getInstance()
  43. .registerCommandExecutionHook(commandExecutionHook);
  44. HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
  45. HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
  46. HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
  47. }
  48. catch (Exception e) {
  49. log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
  50. }
  51. }
  52. private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
  53. HystrixMetricsPublisher metricsPublisher,
  54. HystrixPropertiesStrategy propertiesStrategy) {
  55. if (log.isDebugEnabled()) {
  56. log.debug("Current Hystrix plugins configuration is ["
  57. + "concurrencyStrategy [" + this.delegate + "]," + "eventNotifier ["
  58. + eventNotifier + "]," + "metricPublisher [" + metricsPublisher + "],"
  59. + "propertiesStrategy [" + propertiesStrategy + "]," + "]");
  60. log.debug("Registering Sleuth Hystrix Concurrency Strategy.");
  61. }
  62. }
  63. @Override
  64. public <T> Callable<T> wrapCallable(Callable<T> callable) {
  65. RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
  66. return new WrappedCallable<T>(callable, requestAttributes);
  67. }
  68. @Override
  69. public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
  70. HystrixProperty<Integer> corePoolSize,
  71. HystrixProperty<Integer> maximumPoolSize,
  72. HystrixProperty<Integer> keepAliveTime, TimeUnit unit,
  73. BlockingQueue<Runnable> workQueue) {
  74. return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize,
  75. keepAliveTime, unit, workQueue);
  76. }
  77. @Override
  78. public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
  79. return this.delegate.getBlockingQueue(maxQueueSize);
  80. }
  81. @Override
  82. public <T> HystrixRequestVariable<T> getRequestVariable(
  83. HystrixRequestVariableLifecycle<T> rv) {
  84. return this.delegate.getRequestVariable(rv);
  85. }
  86. static class WrappedCallable<T> implements Callable<T> {
  87. private final Callable<T> target;
  88. private final RequestAttributes requestAttributes;
  89. public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
  90. this.target = target;
  91. this.requestAttributes = requestAttributes;
  92. }
  93. @Override
  94. public T call() throws Exception {
  95. try {
  96. RequestContextHolder.setRequestAttributes(requestAttributes);
  97. return target.call();
  98. }
  99. finally {
  100. RequestContextHolder.resetRequestAttributes();
  101. }
  102. }
  103. }
  104. }

加入此代码之后,必须在启动类 注入 Bean FeignHystrixConcurrencyStrategy 

  1. import com.nmm.study.rpc.FeignHystrixConcurrencyStrategy;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.feign.EnableFeignClients;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
  7. /**
  8. * @author nmm 2018/6/26
  9. * @description
  10. */
  11. @SpringBootApplication
  12. @EnableRedisHttpSession//增加redissession缓存支持
  13. @EnableFeignClients//增加feign支持,引入feign注解,feign扫描路径可以单独指定(basePackages = ),默认是spring的扫描路径
  14. public class ServiceOneApplication {
  15. public static void main(String[] args) {
  16. SpringApplication.run(ServiceOneApplication.class,args);
  17. }
  18. @Bean
  19. public FeignHystrixConcurrencyStrategy feignHystrixConcurrencyStrategy() {
  20. return new FeignHystrixConcurrencyStrategy();
  21. }
  22. }

至此,方可实现 feign调用session丢失的问题完美解决。

本人参与实际项目之中最后虽然使用的通过Header传递信息,还是记录一下以备后面使用。现在主流技术还是使用JWT方式不需要使用Session共享方式。

本文参考了技术大牛的此篇文章:feign调用session丢失解决方案 此文里面有个多余的overwrite方法,同时需要特别注意把bean注入到Application之中

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/476904
推荐阅读
相关标签
  

闽ICP备14008679号