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 ...
随机推荐
- 洛谷.1110.[ZJOI2007]报表统计(Multiset Heap)
题目链接 主要思路 /* 对于询问1,用堆代替multiset/Splay 对于询问2,multiset 1.注意哨兵元素 2.注意multiset中删除时是删除某元素的一个位置,而不是这个元素!这个 ...
- 部分手机(如三星)的Listview列表会自动加上黑线解决办法
部分手机(如三星)的Listview列表会自动加上黑线,这里将其去掉部分手机(如三星)的列表会自动加上黑线. 因为三星手机会自动加上分割线. // 部分手机(如三星C9 Pro)的设置项列表会自动加上 ...
- Android Binder学习的网站
1. Binder系列 http://gityuan.com/2015/10/31/binder-prepare/ 2. Binder机制 http://jcodecraeer.com/a/anzhu ...
- python图片和分形树
链接: 这10个Python项目很有趣! Python 绘制分形图(曼德勃罗集.分形树叶.科赫曲线.分形龙.谢尔宾斯基三角等)附代码 使用Python生成树形图案 神奇的代码:用 Python 生成分 ...
- solr中重建索引(转)
Stop your application server Change your schema.xml file Start your application server Delete the in ...
- Android四大组件应用系列——使用BroadcastReceiver和Service实现倒计时
一.问题描述 Service组件可以实现在后台执行一些耗时任务,甚至可以在程序退出的情况下,让Service在后台继续保持运行状态.Service分本地服务和远程服务,Local地服务附在主进程上的m ...
- 解决PuppetDB Failed to submit 'replace facts'问题
在升级了CentOS6.5后,系统一直运行正常,今天在尝试自动部署了一台新的Bootnode后,发现在运行puppet agent时,发生报错: Error: Could not retrieve c ...
- python3用BeautifulSoup用limit来获取指定数量的a标签
# -*- coding:utf-8 -*- #python 2.7 #XiaoDeng #http://tieba.baidu.com/p/2460150866 #标签操作 from bs4 imp ...
- Notes 和 Domino 已知限制
Notes 和 Domino 已知限制 功能测试 限制数据库的最大大小是多少? 最大的 OS 文件大小限制 -(最大为 64GB)文本域的最大大小是多少? 15KB(存储):15KB,显示在视图列中R ...
- MySQL 5.6新特性 -- crash-safe replication
在slave上有两个线程:io线程和sql线程io线程接收master的二进制日志信息并写入到本地的relay log中:sql线程执行本地relay log中的信息.io线程读取到的二进制日志当前位 ...