feign调用接口session丢失解决方案
微服务使用feign相互之间调用时,因为feign默认不传输Header,存在session丢失的问题。例如,使用Feign调用某个远程API,这个远程API需要传递一个鉴权信息,我们可以把cookie里面的session信息放到Header里面,这个Header是动态的,跟你的HttpRequest相关,我们选择编写一个拦截器来实现Header的传递,也就是需要实现RequestInterceptor接口,详细代码如下:
1.新建feign配置类FeignConfig.java,它包含一个外部hystrix自定义隔离策略类FeignHystrixConcurrencyStrategy.java继承hystrix隔离策略HystrixConcurrencyStrategy ,并且这个自定义策略类作为bean配置到feign的配置类FeignConfig中
package webapp.conf; import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; public class FeignConfig implements RequestInterceptor {
@Bean
public FeignHystrixConcurrencyStrategy feignHystrixConcurrencyStrategy() {
return new FeignHystrixConcurrencyStrategy();
} @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);
}
}
} } } class FeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy { private static final Logger log = LoggerFactory.getLogger(FeignHystrixConcurrencyStrategy.class);
private HystrixConcurrencyStrategy delegate; 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; 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();
}
}
}
}
2.在@FeignClient里配置上面的配置类,如下:
package webapp.userFeign; import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import webapp.conf.FeignConfig; @FeignClient(name = "user", fallback = UserFeignFallBack.class, configuration = FeignConfig.class)
public interface UserFeign {
@RequestMapping(value = "/user/findUser", method = RequestMethod.GET)
String findUser();
@RequestMapping(value = "/user/findLUser", method = RequestMethod.GET)
String findLUser();
}
feign调用接口session丢失解决方案的更多相关文章
- SpringCloud:Feign调用接口不稳定问题以及如何设置超时
1. Feign调用接口不稳定报错 Caused by: java.net.SocketException: Software caused connection abort: recv failed ...
- Vue+elementui +Springboot session丢失解决方案
前后端分离项目 由于端口不一致会出现跨域问题 解决跨域以后又会出现前后端sessionID不一致 首先跨域问题 跨域可以在前端配置代理 proxyTable: { '/': { / ...
- 跨域、跨服务器调用时候session丢失的问题
最近新进一个公司,做的项目是手机支付系统.由于涉及到金钱相关的,所以安全性要求特别的高.项目分了很多个子系统,在部署(测试)的时候是每个Tomcat上面只放一个子系统.比如现在有5个子系统,那么就会对 ...
- Session丢失——解决方案
先抄下别人的作业(原帖:http://www.cnblogs.com/zhc088/archive/2011/07/24/2115497.html) Session丢失已经是一种习以为常的问题了,在自 ...
- spring cloud feign 调用接口报错"No message available
There was an unexpected error (type=Internal Server Error, status=500). status 404 reading HelloServ ...
- Feign 调用丢失Header的解决方案
问题 在 Spring Cloud 中 微服务之间的调用会用到Feign,但是在默认情况下,Feign 调用远程服务存在Header请求头丢失问题. 解决方案 首先需要写一个 Feign请求拦截器,通 ...
- ASP.NET 状态服务 及 session丢失问题解决方案总结
ASP.NET2.0系统时,在程序中做删除或创建文件操作时,出现session丢失问题.采用了如下方法:1.asp.net Session的实现:asp.net的Session是基于HttpModul ...
- [转]ASP.NET 状态服务 及 session丢失问题解决方案总结
转自[http://blog.csdn.net/high_mount/archive/2007/05/09/1601854.aspx] 最近在开发一ASP.NET2.0系统时,在程序中做删除或创建文件 ...
- Bug集锦-Spring Cloud Feign调用其它接口报错
问题描述 Spring Cloud Feign调用其它服务报错,错误提示如下:Failed to instantiate [java.util.List]: Specified class is an ...
随机推荐
- QThreadPool&QRunnable&类函数的使用
QThreadPool+QRunnable线程池与QThread线程两种方式使用的场景不同,QThreadPool+QRunnable线程池主要用于那种不需要一直运行的任务,而QThread主要用于长 ...
- vsftp安装与配置for Linux
以Centos6中使用为例 1.安装 yum -y install vsftpd 2.基本配置 vi /etc/vsftpd/vsftpd.conf 匿名访问和切换根目录都会给服务器带来安全风险,我们 ...
- Internet Explorer 11:不要再叫我IE
上周,Internet Explorer 11搭载Windows 8.1预览版而来,相信很多浏览迷也已经在使用中.Internet Explorer 11 Preview 改进了与 Web 标准.其他 ...
- DotNetty z
使用说明 客户端的代码和服务端的代码相差很少,体现了Netty统一的编程模型.有几个不同点: 客户端的Bootstrap不是ServerBootstrap: 客户端不需要主线程组,只有工作线程组,消息 ...
- 当echarts的legend字数过多的时候变成省略号
legend: { data: ['国有土地使用','食品药品安全','生态环境和资源保护','国有财产保护'], orient: 'horizontal', left: '10', bottom:' ...
- 微软BI 之SSIS 系列 - 平面文件格式的区别(Delimited,Fixed width,Ragged Right, Fixed width ...)
开篇介绍 SSIS 中处理文件,一般在描述输出平面文件格式的时候通常会出现以下几种选项: Delimited - 默认输出列使用逗号分隔,也可以选择其它的诸如 | ,或者 Tab 等. Fixed W ...
- 原创:vsphere概念深入系列四:Nic Teaming若干问题
参考文档:http://www.hyper-v.nu/archives/marcve/2013/01/lbfo-hyper-v-switch-qos-and-actual-performance-pa ...
- postgresql 函数获取多个字段的数字大小值
1.GREATEST(n1,n2,n3,..........) 获取最大值 testdb=#SELECT GREATEST(,,,,,,,,,); +------------------------- ...
- 玩魔兽争霸无故退出 提示框显示"0x21101663"指令引用的"0x02704acc"内存该存不能为"read" 确定就会终止程序
20151002总结:下方法试过,没完全按照说的操作完,觉得有风险且那个read程序执行时间好长的,感觉有点干坏事的意思 ======================================= ...
- Dive into Python
写这篇文章的原因完全是为了督促自己每天晚上看完两章<Dive Into Python>这本书,因此,很多内容都是摘抄自原书的翻译版或者是自己瞎想,于是就顺带着记录了下来.此前已经看完前两章 ...