【问题标题】:Spring Cloud Feign InterceptorSpring Cloud Feign 拦截器
【发布时间】:2015-10-21 17:37:26
【问题描述】:

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

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

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

【问题讨论】:

    标签: java maven spring-cloud netflix-feign


    【解决方案1】:

    如何在 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 {
    
    }
    

    祝你好运

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢@spencergibb。我目前正在使用 org.springframework.cloud:spring-cloud-starter-feign 的 Feign。
      猜你喜欢
      • 2018-02-02
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 2014-05-19
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多