简体   繁体   English

使用新的请求拦截器来假设客户端重试程序?

[英]Feign client Retryer with a new request interceptor?

I am currently building a feign client manually and passing Interceptors to it for authorization. 我目前正在手动构建一个假装客户端并将拦截器传递给它进行授权。 I would like to have a smarter Retryer for some Response code. 我想为一些响应代码提供更智能的Retryer。

public class myErrorEncoder extends ErrorDecoder.Default {

@Override
public Exception decode(final String methodKey, final Response response) {
    if (response.status() == 401) {
        String token = refreshToken();  // I would like to refresh the token and Edit the client
        return new RetryableException("Token Expired will retry it", null);
    } else {
        return super.decode(methodKey, response);
    }
}

} }

Interceptor 拦截器

@Bean public CustomInterceptor getInterceptor(String token) {
    return new CustomInterceptor(token);}

Feign builder 假装建设者

 private <T> T feignBuild(final Class<T> clazz, final String uri, final String token) {
    return Feign
            .builder().client(new ApacheHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new ResponseEntityDecoder(feignDecoder())
            .retryer(new Retryer.Default(1,100,3))
            .errorDecoder(new ErrorDecoder())
            .requestInterceptor(getInterceptor(token))
            .contract(new ClientContract())
            .logger(new Slf4jLogger(clazz)).target(clazz, uri);
}

Now I would like to update feign client with the refreshed token and retry. 现在我想用刷新的令牌更新假装客户端并重试。 Is there a way get access to the client instance and configure it. 有没有办法访问客户端实例并进行配置。

Your use of the interceptor is incorrect. 您对拦截器的使用是不正确的。 Interceptors are re-applied during a retry, but they are instantiated only once and are expected to be thread safe. 在重试期间重新应用拦截器,但它们仅被实例化一次并且预期是线程安全的。 To achieve what you are looking for will need to separate the token generation from the interceptor and have the interceptor request a new token. 要实现您正在寻找的内容,需要将令牌生成与拦截器分开,并让拦截器请求新令牌。

public class TokenInterceptor() {
   TokenService tokenService;

   public TokenInterceptor(TokenService tokenService) {
      this.tokenService = tokenService;
   }

   public void apply(RequestTemplate template) {
      /* getToken() should create a new token */
      String token = this.tokenService.getToken();
      template.header("Authorization", "Bearer " + token);
   }
}

This will ensure that a new token is created each retry cycle. 这将确保每个重试周期都创建一个新令牌。

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

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