Ribbon 部分
Feign底层默认使用了Ribbon.
Ribbon,使用的是LoadBalanceIntercceptor,对请求的路径进行了拦截,拦截到请求后根据该地址从Nacos列表获取真实的地址替换成真实的Ip地址加端口,因为Client本地会维护一份缓存列表,可以通过该列表取注册中心获取地址。
-
关于拦截器的使用.
Screen Shot 2022-01-17 at 12.11.46 PM.png
-
模拟原理
![ Screen Shot 2022-01-17 at 12.10.17 PM.png
Feign 底层封装了Ribbon.
EnableFeignClients 封装了Import注解,导入类FeignClientRegistrar配置类,
然后该实现了BeanDefinitionRegistrar注解.
private void registerFeignClient(BeanDefinitionRegistry registry,
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
String className = annotationMetadata.getClassName();
BeanDefinitionBuilder definition = BeanDefinitionBuilder
.genericBeanDefinition(FeignClientFactoryBean.class);
validate(attributes);
注册的信息中,通过FeignClientFactoryBeanl生成
FeignContext context = applicationContext.getBean(FeignContext.class);
Feign.Builder builder = feign(context);
Targeter targeter = get(context, Targeter.class);
return (T) targeter.target(this, builder, context,
new HardCodedTarget<>(type, name, url));
生成代理对象.
对象是LoadBalancerFeignClient.
然后该对象调用execute的时候,会调用到Ribbon 的方法.
Response execute(Request request, Request.Options options) throws IOException {
try {
URI asUri = URI.create(request.url());
String clientName = asUri.getHost();
URI uriWithoutHost = cleanUrl(request.url(), clientName);
FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(
this.delegate, request, uriWithoutHost);
IClientConfig requestConfig = getClientConfig(options, clientName);
return lbClient(clientName)
.executeWithLoadBalancer(ribbonRequest, requestConfig).toResponse();
底层调用的是Ribbon.
Ribbon源码分析.png- Feign参数如何微调?
OpenFeign相对于Feign主要是增加了对于SpringMVC支持.
具体参数如下
private Logger.Level loggerLevel;
private Integer connectTimeout;
private Integer readTimeout;
private Class<Retryer> retryer;
private Class<ErrorDecoder> errorDecoder;
private List<Class<RequestInterceptor>> requestInterceptors;
private Map<String, Collection<String>> defaultRequestHeaders;
private Map<String, Collection<String>> defaultQueryParameters;
private Boolean decode404;
private Class<Decoder> decoder;
private Class<Encoder> encoder;
private Class<Contract> contract;
private ExceptionPropagationPolicy exceptionPropagationPolicy;
feign:
client:
config:
default:
connectioinTimout: 5000
readTimout: 5000
serviceC:
connectioinTimout: 5000
readTimout: 5000
httpclient: # 替换成ApacheClient或者Okhttp
enable: true
compression: # 开启gzip压缩
request:
enabled: true
min-request-size: 10 #默认开启的压缩阀值是10字节
mime-types: text/html,application/xml,application/json
response:
enabled: true
关于参数额微调:
- 采用okhttp替换原生的httpclient,默认使用了gzip压缩.
- 对于个别的服务,设置微调的超时时间和读取时间.
- 接下来就是对于Okhttp的连接池,参数配置了.
网友评论