使用SpringCloud治理微服务是很方便的,demo级别的应用很容易实现,但是要在生产环境使用的话,需要熟悉其配置,避免采坑。
配置
1、使用okhttp代替默认的HttpClient,配置feign超时时间等
`feign.okhttp.enabled=``true`
`#这是默认设置也可以针对具体的serviceid设置`
`feign.client.config.``default``.connectTimeout=``1000`
`feign.client.config.``default``.readTimeout=``3000`
`feign.client.config.``default``.loggerLevel=basic`
使用okhttp后,必须要设置okhttp的最大idle数量和连接保活时间,不然会导致长连接的频繁关闭,设置如下所示:
|
@Bean
@ConditionalOnProperty``(name = ``"feign.okhttp.enabled"``)
@ConditionalOnMissingBean
public
okhttp3.OkHttpClient getOkHttpClient() {
ConnectionPool connectionPool = ``new
ConnectionPool(maxIdleConnections, keepAliveMiniutes, TimeUnit.MINUTES);
okhttp3.OkHttpClient client = ``new
okhttp3.OkHttpClient.Builder().connectionPool(connectionPool)
.addInterceptor(``new
LoggerInterceptor(``true``))
.build();
return
client;
}
|
2、ribbon的饥饿加载模式
ribbon默认情况下,只有当第一次访问的时候,才会从注册中心加载serviceId的服务信息。
在生产环境下,系统启动后,如果瞬间流量大的话,会导致请求处理缓慢的情况。
建议生产环境下,采用预加载模式。配置如下所示:
|
ribbon.eager-load.enabled=``true
ribbon.eager-load.clients=spring-cloud-service #此处配置需要预加载的serviceId,逗号分隔
|
3、启用hystrix断路器功能
|
feign.hystrix.enabled=``true
|
使用hystrix的需要实现对应的接口方法,做降级处理。
日常开发中,如果针对每个接口都写一个实现fallback的方法会很麻烦,我们针对hystrix定制统一的fallback处理方法,返回json对象或者错误消息。如果有个性话的fallback,再单独实现接口。
4、使用feign拦截器,给上游请求添加统一的header信息
5、使用okhttp拦截器,打印请求日志
6、feign返回结果使用json编解码
feign可以使用feign-gson类库实现对请求返回结果进行json序列化。
配置如下所示:
|
需要单独引入包:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>``10.10``.``1``</version>
</dependency>
@Bean
@ConditionalOnProperty``(name = ``"feign.decoder.json.enabled"``, matchIfMissing = ``true``)
@ConditionalOnMissingBean
public
Decoder feignDecoder() {
return
new
GsonDecoder();
}
@Bean
@ConditionalOnProperty``(name = ``"feign.encoder.json.enabled"``, matchIfMissing = ``true``)
@ConditionalOnMissingBean
public
Encoder feignEncoder() {
return
new
GsonEncoder();
}
|
使用feign-gson后,接口的返回值必须得是json格式,否则会出现反序列化异常。
本demo使用fastjson类库实现定制化的json decoder,并且解决接口返回String类型数据的情况。
需要关注的问题
1、服务的降级处理、熔断处理,配置合理的阀值
2、nacos注册中心默认的心跳时间是5秒
具体参考spring-cloud-demo:
git@inside-git.01zhuanche.com:tg-public/spring-cloud-demo.git