在微服务环境下,远程调用feign和异步线程存在请求数据丢失问题
一、无异步线程得情况下feign远程调用:
0、登录拦截器:
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
public static ThreadLocal<MemberResVo> loginUser = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //获取登录用户的键
MemberResVo attribute = (MemberResVo) request.getSession().getAttribute(AuthServerConstant.LONG_USER);
if (attribute!=null){
loginUser.set(attribute);
return true;
}else {
request.getSession().setAttribute("msg","请先进行登录!");
response.sendRedirect("http://auth.gulimall.com/login.html");
return false;
}
}
}
1、问题示例图:

解决方法:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Configuration
public class GuliFeignConfig {
//fegin过滤器
@Bean("requestInterceptor")
public RequestInterceptor requestInterceptor() {
return new RequestInterceptor() {
public void apply(RequestTemplate template) {
//上下文环境保持器,拿到刚进来这个请求包含的数据,而不会因为远程数据请求头被清除
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();//老的请求
if (request != null) {
//同步老的请求头中的数据,这里是获取cookie
String cookie = request.getHeader("Cookie");
template.header("Cookie", cookie);
}
}
};
}
}
二、异步情况下丢失上下文问题:

① 在同一线程下进行远程调用,即一连串调用的情况下OrederService通过远程调用先查找adress信息,再查找cart信息,则仅需配置GuliFeignConfig就够了
② 由于采用的异步任务,所以101、102线程在自己的线程中调用登录拦截器interceptor,而其实只有在72号线程中登陆拦截器才进行放行(有请求头数据),这就导致101、102的request为null
解决方式(高亮部分):从总线中获取request数据放入子线程中
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
@Autowired
MemberFeignService memberFeignService;
@Autowired
CartFeginService cartFeginService;
@Autowired
ThreadPoolExecutor executor;
@Autowired
WmsFeignService wmsFeignService;
/**
* 订单确认页返回的数据
* @return
*/
@Override
public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
OrderConfirmVo confirmVo = new OrderConfirmVo();
MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();
//从主线程中获得所有request数据
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
//1、远程查询所有地址列表
RequestContextHolder.setRequestAttributes(requestAttributes);
List<MemberAddressVo> address = memberFeignService.getAddress(memberResVo.getId());
confirmVo.setAddress(address);
}, executor);
//2、远程查询购物车所选的购物项,获得所有购物项数据
CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
//放入子线程中request数据
RequestContextHolder.setRequestAttributes(requestAttributes);
List<OrderItemVo> items = cartFeginService.getCurrentUserCartItems();
confirmVo.setItem(items);
}, executor).thenRunAsync(()->{
RequestContextHolder.setRequestAttributes(requestAttributes);
List<OrderItemVo> items = confirmVo.getItem();
List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
//远程调用查询是否有库存
R hasStock = wmsFeignService.getSkusHasStock(collect);
//形成一个List集合,获取所有物品是否有货的情况
List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
});
if (data!=null){
//收集起来,Map<Long,Boolean> stocks;
Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
confirmVo.setStocks(map);
}
},executor);
//feign远程调用在调用之前会调用很多拦截器,因此远程调用会丢失很多请求头
//3、查询用户积分
Integer integration = memberResVo.getIntegration();
confirmVo.setIntegration(integration);
//其他数据自动计算
CompletableFuture.allOf(getAddressFuture,cartFuture).get();
return confirmVo;
}
}
在微服务环境下,远程调用feign和异步线程存在请求数据丢失问题的更多相关文章
- 2流高手速成记(之八):基于Sentinel实现微服务体系下的限流与熔断
我们接上回 上一篇中,我们进行了简要的微服务实现,也体会到了SpringCloudAlibaba的强大和神奇之处 我们仅改动了两个注释,其他全篇代码不变,原来的独立服务就被我们分为了provider和 ...
- 032 搭建搜索微服务01----向ElasticSearch中导入数据--通过Feign实现微服务之间的相互调用
1.创建搜索服务 创建module: Pom文件: <?xml version="1.0" encoding="UTF-8"?> <proje ...
- 微服务架构 | 4.2 基于 Feign 与 OpenFeign 的服务接口调用
目录 前言 1. OpenFeign 基本知识 1.1 Feign 是什么 1.2 Feign 的出现解决了什么问题 1.3 Feign 与 OpenFeign 的区别与对比 2. 在服务消费者端开启 ...
- 客户端远程调用Feign
客户端远程调用 Feign 什么是Feign? Feign是 Netflix 公司开源的声明式HTTP客户端 Github : Feign 源码 为什么需要Feign? 原代码可读性不高 复杂的URL ...
- TOP100summit:【分享实录-华为】微服务场景下的性能提升最佳实践
本篇文章内容来自2016年TOP100summit华为架构部资深架构师王启军的案例分享.编辑:Cynthia 王启军:华为架构部资深架构师.负责华为的云化.微服务架构推进落地,前后参与了华为手机祥云4 ...
- 微服务架构下分布式Session管理
转载本文需注明出处:EAII企业架构创新研究院(微信号:eaworld),违者必究.如需加入微信群参与微课堂.架构设计与讨论直播请直接回复此公众号:“加群 姓名 公司 职位 微信号”. 一.应用架构变 ...
- SpringBoot微服务架构下的MVC模型总结
SpringBoot微服务架构下的MVC模型产生的原因: 微服务概念改变着软件开发领域,传统的开源框架结构开发,由于其繁琐的配置流程 , 复杂的设置行为,为项目的开发增加了繁重的工作量,微服务致力于解 ...
- 微服务架构下分布式事务解决方案——阿里GTS
1 微服务的发展 微服务倡导将复杂的单体应用拆分为若干个功能简单.松耦合的服务,这样可以降低开发难度.增强扩展性.便于敏捷开发.当前被越来越多的开发者推崇,很多互联网行业巨头.开源社区等都开始了微服务 ...
- 微服务架构下分布式事务解决方案——阿里云GTS
https://blog.csdn.net/jiangyu_gts/article/details/79470240 1 微服务的发展 微服务倡导将复杂的单体应用拆分为若干个功能简单.松耦合的服务,这 ...
- 微服务架构下 CI/CD 如何落地
本文系云原生应用最佳实践杭州站活动演讲稿整理.杭州站活动邀请了 Apache APISIX 项目 VP 温铭.又拍云平台开发部高级工程师莫红波.蚂蚁金服技术专家王发康.有赞中间件开发工程师张超,分享云 ...
随机推荐
- 一次查找分子级Bug的经历,过程太酸爽了
"Debugging is like trying to find a needle in a haystack, except the needle is also made of hay ...
- 如何通过CAD图中的坐标来确定是哪个坐标系
国内常见的坐标系 坐标系分为以下两种: 地理坐标系(Geographic Coordinate System, GCS) 投影坐标系(Projected Coordinate System, PCS) ...
- UpSetR 高级参数使用教程
在<UpSetR:多数据集绘图可视化处理利器>中我们介绍了 UpSetR 的一些概念和绘图基础参数使用,今天我们来学习一下 UpSetR 的 queries 和 attribute.plo ...
- Bioconductor 中的 R 包安装教程
Bioconductor 是一个基于 R 语言的生物信息软件包,主要用于生物数据的注释.分析.统计.以及可视化(http://www.bioconductor.org). 总所周知,Bioconduc ...
- Kafka的系统架构和API开发
系统架构 主题topic和分区partition topic Kafka中存储数据的逻辑分类:你可以理解为数据库中"表"的概念:比如,将app端日志.微信小程序端日志.业务库订单表 ...
- JVM源码分析:深入剖析java.c文件中JavaMain方法中InitializeJVM的实现
经过前文<从JDK源码级深入剖析main方法的运行机制>的分析,我们知道了实现JavaMain方法的四个主要步骤: 初始化Java虚拟机 加载主运行类 通过加载的主运行类,获取main方法 ...
- React SSR - 写个 Demo 一学就会
React SSR - 写个 Demo 一学就会 今天写个小 Demo 来从头实现一下 react 的 SSR,帮助理解 SSR 是如何实现的,有什么细节. 什么是 SSR SSR 即 Server ...
- 反转链表 Java版 图文并茂思路分析带答案(力扣第206题)
反转链表 力扣第206题 我们不只是简单的学习(背诵)一个数据结构,而是要分析他的思路,以及为什么要有不同的指针等等 非递归方式: 思路分析:首先要链表有个头指针没有任何问题 然后,我们要将1的下一个 ...
- W1R3S-1项目实战
前言 您受聘在W1R3S.inc单个服务器上进行渗透测试,并报告所有发现.他们要求您获得root访问权限并找到标志(位于/root目录中). 难以获得低特权外壳:初级/中级 获得特权升级的难度:初级/ ...
- GO web学习(三)
跟着b站https://space.bilibili.com/361469957 杨旭老师学习做的笔记 路由 Controller / Router 角色 main():设置类工作 controlle ...