8

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

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

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

4

2 回答 2

3

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

  1. Client通过扩展创建自定义,Client.Default如下所示:
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 {

}

祝你好运

于 2020-06-11T14:39:55.817 回答
1

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

于 2015-07-30T17:32:17.073 回答