hystrix线程切换后获取不到安全上下文的坑

1 篇文章 0 订阅
1 篇文章 0 订阅

报错

Error creating bean with name 'scopedTarget.oauth2ClientContext': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton

解决方案

  1. 取消熔断
    feign.hystrix.enabled=false
  2. 切换隔离等级
    hystrix.command.default.execution.isolation.strategy=SEMAPHORE
  3. 线程间传递上下文
    a. hystrix.shareSecurityContext=true
    b. 注入自定义RequestInterceptor, 在请求中设定HTTP header
@Bean
public RequestInterceptor oAuth2RequestInterceptor() {
    return template -> {
        // 在org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter
        // 过滤器中,已经将OAuth2Authentication放大了请求上下文中,所以没有使用instanceof判断
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder
                .getContext().getAuthentication();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oAuth2Authentication.getDetails();
        template.header("Authorization", details.getTokenType() + " " + details.getTokenValue());
    };
} 
  1. 在代码内有线程切换的情况下(比如使用paralleStream),需要在线程内设置上下文
SecurityContext context = SecurityContextHolder.getContext();
List<Integer> list = xxxxService.findByxxxx(xxxx);
list.parallelStream().forEach(
	SecurityContextHolder.setContext(context);
	l -> xxxxClient.findByXxxx(l); // 请求其他服务的接口
);

原因

请求
获取callable接口的实现类,可以看到获取了父线程的上下文
在子线程获取父线程的上下文
在新线程中先设定请求上下文
在新线程中先设定请求上下文

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值