1、feign远程调用导致请求头丢失问题
如何解决?
加上feign远程调用的请求拦截器
/**
* @author houChen
* @date 2022/2/3 17:20
* @Description: 谷粒商城feign请求的相关配置
*/
@Configuration
public class GuliFeignConfig {
@Bean("requestInterceptor")
public RequestInterceptor requestInterceptor(){
return new RequestInterceptor(){
@Override
public void apply(RequestTemplate template) {
//1、RequestContextHolder拿到刚进来的请求
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest(); //老请求
//2、同步请求头数据 cookie
String cookie = request.getHeader("cookie");
template.header("cookie",cookie);
}
};
}
}
2、异步Feign调用丢失请求头问题
在一个请求的执行过程中,如果有一个新的异步请求出来执行别的任务,那么在该新的请求中是拿不到老的请求的
上下文环境的。
可以在新的上下文环境中将老的上下文环境赋值过去
@Override
public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(()->{
//解决异步feign请求丢失请求头问题
RequestContextHolder.setRequestAttributes(requestAttributes);
//1、远程查询所有的收货地址列表
List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
orderConfirmVo.setAddress(address);
}, executor);
CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(() -> {
RequestContextHolder.setRequestAttributes(requestAttributes);
//2、远程查询购物车所有选中的购物项
List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
orderConfirmVo.setItems(currentUserCartItems);
}, executor);
CompletableFuture.allOf(completableFuture1,completableFuture2).get();
//3、查询用户积分
Integer integration = memberRespVo.getIntegration();
orderConfirmVo.setIntegration(integration);
//4、其他数据自动计算
//5、todo 防订单重复提交令牌
return orderConfirmVo;
}