Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Spring Cloud OpenFeign 使用指定配置

Spring Boot OpenFeign 大约 1876 字

需求

因为OpenFeign被添加在公共库中,且注入到了全局Decoder,所有Feign客户端都使用了@Decoder

有特殊的客户端不适用全局Decoder,指定另外配置。

本文基于openfeign3.0.5

自定义配置

messageConvertersSpringMVC框架默认注入,我们可以直接使用

import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import java.io.IOException;
import java.lang.reflect.Type;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;

@RequiredArgsConstructor
public class TestFeignConfig {

    private final ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Decoder specificDecoder() {
        return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(messageConverters)) {
            @Override
            public Object decode(Response response, Type type) throws IOException, FeignException {
                // 逻辑处理
                return super.decode(response, type);
            }
        });
    }

}

指定配置

使用@FeignClient中的configuration指定自定义配置。

@FeignClient(name = "test-feign-client", url = "${test.url}", configuration = TestFeignConfig.class)
public interface TestFeignClient {
    // ...
}

OpenFeign 默认配置

FeignClientsConfiguration类是OpenFeign使用的默认配置。

可以看到如果没有注入全局的Decoder,则OpenFeign会触发@ConditionalOnMissingBean条件,注入默认Decoder

// org.springframework.cloud.openfeign.FeignClientsConfiguration
@Configuration(proxyBeanMethods = false)
public class FeignClientsConfiguration {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    // ...

    @Bean
    @ConditionalOnMissingBean
    public Decoder feignDecoder() {
        return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
    }

}
阅读 109 · 发布于 2022-10-24

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批