热门标签 | HotTags
当前位置:  开发笔记 > 开发工具 > 正文

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

这篇文章主要介绍了详解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 headerNames = request.getHeaderNames(); 
  if (headerNames != null) { 
   while (headerNames.hasMoreElements()) { 
    String name = headerNames.nextElement(); 
    Enumeration 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.
 * 

* 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. *

* 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. *

* See {@link HystrixPlugins} or the Hystrix GitHub Wiki for information on configuring plugins: https://github.com/Netflix/Hystrix/wiki/Plugins. */ 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  Callable wrapCallable(Callable callable) { 
  RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); 
  return new WrappedCallable<>(callable, requestAttributes); 
 } 
 
 @Override 
 public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, 
   HystrixProperty corePoolSize, HystrixProperty maximumPoolSize, 
   HystrixProperty keepAliveTime, TimeUnit unit, BlockingQueue 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 getBlockingQueue(int maxQueueSize) { 
  return this.delegate.getBlockingQueue(maxQueueSize); 
 } 
 
 @Override 
 public  HystrixRequestVariable getRequestVariable(HystrixRequestVariableLifecycle rv) { 
  return this.delegate.getRequestVariable(rv); 
 } 
 
 static class WrappedCallable implements Callable { 
  private final Callable target; 
  private final RequestAttributes requestAttributes; 
 
  public WrappedCallable(Callable 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丢失的问题完美解决。

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


推荐阅读
  • 本文基于对相关论文和开源代码的研究,详细介绍了LOAM(激光雷达里程计与建图)的工作原理,并对其关键技术进行了分析。 ... [详细]
  • 资源推荐 | TensorFlow官方中文教程助力英语非母语者学习
    来源:机器之心。本文详细介绍了TensorFlow官方提供的中文版教程和指南,帮助开发者更好地理解和应用这一强大的开源机器学习平台。 ... [详细]
  • 构建基于BERT的中文NL2SQL模型:一个简明的基准
    本文探讨了将自然语言转换为SQL语句(NL2SQL)的任务,这是人工智能领域中一项非常实用的研究方向。文章介绍了笔者在公司举办的首届中文NL2SQL挑战赛中的实践,该比赛提供了金融和通用领域的表格数据,并标注了对应的自然语言与SQL语句对,旨在训练准确的NL2SQL模型。 ... [详细]
  • 数据库内核开发入门 | 搭建研发环境的初步指南
    本课程将带你从零开始,逐步掌握数据库内核开发的基础知识和实践技能,重点介绍如何搭建OceanBase的开发环境。 ... [详细]
  • 本文介绍如何使用 Sortable.js 库实现元素的拖拽和位置交换功能。Sortable.js 是一个轻量级、无依赖的 JavaScript 库,支持拖拽排序、动画效果和多种插件扩展。通过简单的配置和事件处理,可以轻松实现复杂的功能。 ... [详细]
  • 探讨一个显示数字的故障计算器,它支持两种操作:将当前数字乘以2或减去1。本文将详细介绍如何用最少的操作次数将初始值X转换为目标值Y。 ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • 本文详细介绍了如何在 Spring Boot 应用中通过 @PropertySource 注解读取非默认配置文件,包括配置文件的创建、映射类的设计以及确保 Spring 容器能够正确加载这些配置的方法。 ... [详细]
  • This document outlines the recommended naming conventions for HTML attributes in Fast Components, focusing on readability and consistency with existing standards. ... [详细]
  • 在现代网络环境中,两台计算机之间的文件传输需求日益增长。传统的FTP和SSH方式虽然有效,但其配置复杂、步骤繁琐,难以满足快速且安全的传输需求。本文将介绍一种基于Go语言开发的新一代文件传输工具——Croc,它不仅简化了操作流程,还提供了强大的加密和跨平台支持。 ... [详细]
  • 解决微信电脑版无法刷朋友圈问题:使用安卓远程投屏方案
    在工作期间想要浏览微信和朋友圈却不太方便?虽然微信电脑版目前不支持直接刷朋友圈,但通过远程投屏技术,可以轻松实现在电脑上操作安卓设备的功能。 ... [详细]
  • 本文详细介绍了Java中org.eclipse.ui.forms.widgets.ExpandableComposite类的addExpansionListener()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。这些示例来源于多个知名开源项目,具有很高的参考价值。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • Android LED 数字字体的应用与实现
    本文介绍了一种适用于 Android 应用的 LED 数字字体(digital font),并详细描述了其在 UI 设计中的应用场景及其实现方法。这种字体常用于视频、广告倒计时等场景,能够增强视觉效果。 ... [详细]
  • RecyclerView初步学习(一)
    RecyclerView初步学习(一)ReCyclerView提供了一种插件式的编程模式,除了提供ViewHolder缓存模式,还可以自定义动画,分割符,布局样式,相比于传统的ListVi ... [详细]
author-avatar
mobiledu2502884483
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有