Spring Cloud OpenFeign 使用指定配置
Spring Boot OpenFeign About 1,876 words需求
因为OpenFeign
被添加在公共库中,且注入到了全局Decoder
,所有Feign
客户端都使用了@Decoder
。
有特殊的客户端不适用全局Decoder
,指定另外配置。
本文基于openfeign3.0.5
。
自定义配置
messageConverters
为SpringMVC
框架默认注入,我们可以直接使用
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)));
}
}
Views: 1,563 · Posted: 2022-10-24
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...