线程调用feign时解决token丢失的情况

2023-04-19  本文已影响0人  thinking2019

直接上代码

// 在线程外部获取到requestAttributes
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// 线程池调用
executorService.submit(() -> {
    // 然后在在线程内部将requestAttributes 设置到RequestContextHolder中去
    RequestContextHolder.setRequestAttributes(requestAttributes);
    //将主线程的token更新到子线程全局变量中
    assert requestAttributes != null;
    ThreadLocalUtil.set("token", requestAttributes.getRequest().getHeader("token"));

    // 方法主体
    return xxxx();
});

FeignConfig

public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String token= request.getHeader("token");
        if (StringUtils.isBlank(token)){
            // 重点
            token= ThreadLocalUtil.get("token");
        }
        log.info("token={}", token);

        //添加token
        requestTemplate.header("token", token);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读