简体   繁体   English

在RestTemplate拦截器中调用execution.execute()两次

[英]Calling execution.execute() twice in RestTemplate interceptor

I have to integrate with external service that requires access token to be sent with each requests. 我必须与需要访问令牌的外部服务集成,以便与每个请求一起发送。 Access token has a short expiration time (only a few hours). 访问令牌的到期时间很短(只有几个小时)。 I've decided to use access token in optimistic way. 我决定以乐观的方式使用访问令牌。 I'm going to call external service with current token. 我将使用当前令牌调用外部服务。 I case of getting 401 I'm going to refresh the token and call the external API one more time. 我获得401的情况我将刷新令牌并再次调用外部API。

I've decided to use ClientHttpRequestInterceptor to implement described retry mechanism. 我决定使用ClientHttpRequestInterceptor来实现所描述的重试机制。

public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
   ClientHttpResponse response = execution.execute(request, body);
   if(response.getStatusCode() == UNAUTHORIZED) {
       refreshToken();
       updateToken(request);
       response = execution.execute(request, body);
   }
   return response;
}

I have tested it and it works, but is it allowed to call execution.execute() twice? 我测试了它并且它可以工作,但它是否允许调用execution.execute()两次? I haven't found any information that it's forbidden, but from the other hand I haven't seen such code as well. 我没有找到任何被禁止的信息,但另一方面我还没有看到这样的代码。

we are doing exactly the same - and having issues. 我们做的完全一样 - 并且有问题。 This snippet of code you have there will leak connections as the original response is ignored and not closed properly. 您在那里的这段代码将泄漏连接,因为原始响应被忽略而未正确关闭。 My current solution is to explicitly close it and then do the second execution. 我目前的解决方案是明确关闭它,然后执行第二次执行。 Seems to work so far but I guess it needs more evaluation. 似乎到目前为止工作,但我想它需要更多的评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM