背景
微服务应用大多对外提供RESTful API,需要有相应的token才能访问,我们在聚合服务中使用Feign Client调用这些API,顺序执行往往会浪费大量的IO等待时间,为了提高查询速度,我们会使用异步调用,Java 8引入了CompletableFuture,结合Executor框架大大简化了异步编程的复杂性。
问题描述
我们的服务使用Spring Security OAuth2授权,并通过JWT传递token,对于用户侧的请求一律使用用户token,后端服务间的调用使用系统token。但有时为了简化开发(如用户信息传递),服务间调用仍然传递用户token。这就带来一个问题,在异步请求中子线程会丢失相应的认证信息,错误如下:
org.springframework.beans.factory.BeanCreationException: 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;
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:365)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:192)
at com.sun.proxy.$Proxy170.getAccessToken(Unknown Source)
at org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor.getToken(OAuth2FeignRequestInterceptor.java:126)
at org.springfram