Feign携带Token及多线程下鉴权失败的问题

Feign携带鉴权Token

  1. 新增拦截器类,拦截当前请求获取Header中鉴权token,添加到后续请求的Header中
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes!=null){
            HttpServletRequest request = attributes.getRequest();
            //添加token
            requestTemplate.header("Authorization", request.getHeader("Authorization"));
        }
    }
}
  1. 对指定的@FeignClient添加拦截器
@FeignClient(name = "xxx", configuration = {FeignConfig.class})

多线程下鉴权失败

场景:服务A的方法多次调用服务B的方法,报超时异常,在不想改动服务B的前提下:

  1. 配置Feign超时时间,无果。
feign.client.config.default.connectTimeout=5000
feign.client.config.default.read-timeout=30000。
  1. 考虑用多线程调用,之前配置的拦截器失效,无法正确携带Token导致鉴权失败。原因大致是子线程中无法获取到RequestAttributes,于是在主线程中取获取RequestAttributes,再传入子线程。

主线程:

// 主线程: 获取所有request数据
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
LastDataTimeThread handleThread = new LastDataTimeThread(cards, i * tl, endIndex > length ? length : endIndex, countDownLatch,requestAttributes);
handleThread.start();

线程类:

@Override
public void run() {
	RequestContextHolder.setRequestAttributes(requestAttributes);
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值