Hystrix 的默认超时时间 :1s
OpenFeign底层是使用 ribbon实现的 默认连接超时时间 : 1s
修改连接超时时间配置(OpenFeign):
#设置feign客户端超时时间
ribbon:
ReadTimeout: 6000 #指的是建立连接所用得时间,适用于网络状况正常的情况下,两端连接所用的时间(6s)
ConnectTimeout: 6000 #指的是建立连接后从服务器读取到可用资源所用的时间(6s)
修改Hystrix超时时间(即达到服务降级时间)配置:
hystrix:
command:
default:
execution:
isolation:
thread:
#feign整合hystrix 光设置Hystrix超时没用的 要配合ribbon超时
timeoutInMilliseconds: 6000
被调用服务(服务端)使用 Hystrix(断路器)的配置:
添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
1.在启动类加上注解: @EnableCircuitBreaker
2.在application.yml中修改超时时间(即服务降级时间的阈值)
3.在service实现类中某个方法中实现服务降级配置
(1) 方法指定服务降级方法的配置(即一个方法配置一个服务降级方法)
@HystrixCommand(fallbackMethod = "paymentInfo_timeOutHandler",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
})
其中 paymentInfo_timeOutHandler 是服务降级后执行的方法; value 是服务降级的阈值(时间 5s)。
4.通用服务降级的配置(即 任何方法都共用一个服务降级的方法)
(1)在service类前加入注解 @DefaultProperties(defaultFallback = “payment_global_fallback_method”
其中 payment_global_fallback_method 是服务降级后执行的方法
(2)在需要进行服务降级的方法前加入注解 @HystrixCommand 即可。
(3)此时的服务降级阈值(时间)根据application.yml所配置(若没配置,则使用默认时间1s)的降级阈值时间判断是否需要对服务进行降级。
实现调用端(客户端)
添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
application 配置:
#允许服务降级配置
feign:
hystrix:
enabled: true
#设置feign客户端超时时间
ribbon:
ReadTimeout: 6000 #指的是建立连接所用得时间,适用于网络状况正常的情况下,两端连接所用的时间(5s)
ConnectTimeout: 6000 #指的是建立连接后从服务器读取到可用资源所用的时间(5s)
hystrix:
command:
default:
execution:
isolation:
thread:
#feign整合hystrix 光设置Hystrix超时没用的 要配合ribbon超时
timeoutInMilliseconds: 6000
在启动类上加入注解@EnableHystrix
降级服务配置:类似服务端的配置。
注:此处涉及三处的服务降级的阈值时间。
1.application中配置的 hystrix (或者没配置,则是默认)阈值时间
2.application中配置的 ribbon (OpenFeign)连接超时阈值时间
3. @HystrixCommand 中设置的服务降级阈值的时间
系统会根据这三个时间中最小的时间判断是否需要进行服务降级。如 hystrix 配置为3s, ribbon 配置为5s, @HystrixCommand 设置为2s,则服务等待时间超过2s后则进行服务降级