简体   繁体   中英

Feign response interceptor using Spring Cloud OpenFeign

Feign now supports ResponseInterceptor class. Can I somehow implement it using Spring Cloud Feign or I need to use Feign.builder()?

Tried like this in my custom FeignConfig:

@Bean
public ClientResponseInterceptor responseInterceptor() {
    return new ClientResponseInterceptor();
}

But seems not working. Any ideas how to inject custom ResponseInterceptor?

I dit not succeeded in using the ResponseInterceptor.

But I've found an alternative using the feign.codec.Decoder .

In this example, I'm reading the Content-Language of every Feign client responses:

public class ClientResponseInterceptor implements Decoder {

    private final JacksonDecoder delegate;

    public ClientResponseInterceptor(JacksonDecoder delegate) {
        this.delegate = delegate;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        String contentLanguageFromFeignResponse;

        Collection<String> contentLanguage = response.headers().get(HttpHeaders.CONTENT_LANGUAGE);
        // Extract this part in another method
        if (contentLanguage != null && !contentLanguage.isEmpty()) {
            Optional<String> attributeOpt = contentLanguage.stream().findFirst();
            if (attributeOpt.isPresent()) {
                contentLanguageFromFeignResponse = attributeOpt.get();
            }
        }

        // Do something with contentLanguageFromFeignResponse

        return delegate.decode(response, type);
    }
}

And declaring it in your feign config file:

@Bean
public ClientResponseInterceptor responseInterceptor() {
    return new ClientResponseInterceptor(new JacksonDecoder(/*objectMapper*/));
}

(You can use another Decoder, JacksonDecoder is just an example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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