报错
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
解决方案
- 取消熔断
feign.hystrix.enabled=false
- 切换隔离等级
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
- 线程间传递上下文
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());
};
}
- 在代码内有线程切换的情况下(比如使用paralleStream),需要在线程内设置上下文
SecurityContext context = SecurityContextHolder.getContext();
List<Integer> list = xxxxService.findByxxxx(xxxx);
list.parallelStream().forEach(
SecurityContextHolder.setContext(context);
l -> xxxxClient.findByXxxx(l); // 请求其他服务的接口
);
原因
获取callable接口的实现类,可以看到获取了父线程的上下文
在新线程中先设定请求上下文