繁体   English   中英

Spring Cloud Feign 拦截器

[英]Spring Cloud Feign Interceptor

我创建了一个 ClientHttpRequestInterceptor,用于拦截所有传出的 RestTemplate 请求和响应。 我想将拦截器添加到所有传出的 Feign 请求/响应中。 有没有办法做到这一点?

我知道有一个 feign.RequestInterceptor 但是这样我只能拦截请求而不是响应。

我在 Github 中找到了一个 FeignConfiguration 类,它可以添加拦截器,但我不知道它在哪个 maven 依赖版本中。

如何在 Spring Cloud OpenFeign 中拦截响应的实际示例。

  1. 通过扩展Client.Default创建一个自定义Client ,如下所示:
public class CustomFeignClient extends Client.Default {


    public CustomFeignClient(SSLSocketFactory sslContextFactory, HostnameVerifier hostnameVerifier) {
        super(sslContextFactory, hostnameVerifier);
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {

        Response response = super.execute(request, options);
        InputStream bodyStream = response.body().asInputStream();

        String responseBody = StreamUtils.copyToString(bodyStream, StandardCharsets.UTF_8);

        //TODO do whatever you want with the responseBody - parse and modify it

        return response.toBuilder().body(responseBody, StandardCharsets.UTF_8).build();
    }
}
  1. 然后在配置类中使用自定义Client
public class FeignClientConfig {


    public FeignClientConfig() { }

    @Bean
    public Client client() {
        return new CustomFeignClient(null, null);
    }

}
  1. 最后,在 FeignClient 中使用配置类:
@FeignClient(name = "api-client", url = "${api.base-url}", configuration = FeignClientConfig.class)
public interface ApiClient {

}

祝你好运

如果您想使用 spring cloud 中的org.springframework.cloud:spring-cloud-starter-feign ,请使用org.springframework.cloud:spring-cloud-starter-feign作为您的依赖坐标。 目前修改响应的唯一方法是实现你自己的feign.Client

暂无
暂无

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

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