默认情况下, Spring Boot 使用 Tomcat 来作为内嵌的 Servlet 容器, 可以将 Web 服务器切换到 Undertow 来提高应用性能, Undertow 是红帽公司开发的一款基于 NIO 的高性能 Web 嵌入式。
Zuul使用的内置容器默认是Tomcat, 可以将其换成undertow, 可以显著减少线程的数量。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-undertowartifactId>
dependency>
server:
undertow:
io-threads: 16
worker-threads: 256
buffer-size: 1024
buffers-per-region: 1024
direct-buffers: true
feign 默认不启用hystrix, feign.hystrix.enabled=true 开启熔断。
feign 启用压缩也是一种有效的性能优化方式。
feign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
response:
enabled: true
feign HTTP请求方式选择。
feign默认使用的是基于JDK提供的URLConnection调用HTTP接口, 无线程池, Apache HttpClient
和okhttp
都支持配置连接池功能, 也可以使用okhttp请求方式。
HttpClient:
feign:
httpclient:
enabled: true
max-connections:1000
max-connections-per-route: 200
okHttp:
feign:
okhttp:
enabled: true
httpclient:
max-connections: 1000
max-connections-per-route: 200
Hystrix有隔离策略: THREAD 以及SEMAPHORE, 默认是 SEMAPHORE 。
Zuul默认是使用信号量隔离, 信号量数量为100, 请求的并发线程超过100就会报错。
zuul:
semaphore:
max-semaphores: 5000
为了方便ThreadLocal的使用, 可以改变隔离策略, 需要调大hystrix的线程池大小。
zuul:
ribbonIsolationStrategy: THREAD
hystrix:
threadpool:
default:
coreSize: 100
maximumSize: 400
allowMaximumSizeToDivergeFromCoreSize: true
maxQueueSize: -1
需要设置参数hystrix.threadpool.default.coreSize 来指定熔断隔离的线程数, 这个数需要调优。
hystrix:
threadpool:
default:
coreSize: 500
command:
default:
circuitBreaker:
requestVolumeThreshold: 1000
fallback:
enabled: true
execution:
isolation:
thread:
timeoutInMilliseconds: 100000
Ribbon进行客户端负载均衡的Client并不是在服务启动的时候就初始化好的, 而是在调用的时候才会去创建相应的Client, 所有第一次调用的耗时不仅仅包含发送HTTP请求的时间, 还包括了创建RibbonClient的时间。
ribbon:
eager-load:
enabled:true
clients:service-1,service-2,service-n