簡體   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