如何解决RestTemplate 拦截器线程安全?
在 this tutorial 中,作者为 RestTemplate
中的 @Controller
使用了一个全局变量。
对于传入的请求,他从请求中提取 Bearer 令牌,并添加一个拦截器,将令牌添加到 RestTemplate
的传出请求中。
我认为,可能存在竞争条件。第二个用户的请求可能会从第一个用户那里获得拦截器,因此作为第一个用户进行身份验证。
据 Okta 称,他们测试了代码并且没有遇到任何竞争条件。 Spring 中是否有某种机制可以确保这一点?
解决方法
RestTemplate
本身 is thread safe。
有问题的代码:
restTemplate.getInterceptors().add(getBearerTokenInterceptor(accessToken.getTokenValue()));
... 看起来确实有问题。我不确定,因为我没有尝试查看它是用于单元测试还是集成测试。
来自the getInterceptors()
Javadoc:
/**
* Get the request interceptors that this accessor uses.
* <p>The returned {@link List} is active and may be modified. Note,* however,that the interceptors will not be resorted according to their
* {@linkplain AnnotationAwareOrderComparator#sort(List) order} before the
* {@link ClientHttpRequestFactory} is built.
*/
您可以尝试改用 setInterceptors()
,因为它取代了拦截器。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。