第一步: 添加依赖
<!-- spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
第二步: 在入口类中使用 @EnableCircuitBreaker 注解或 @EnableHystrix开启断路器功能,也可以使用一个名为 @SpringCloudApplication 的注解代替主类上的三个注解;
第三步: 在调用远程服务的方法上添加注解:@HystrixCommand(fallbackMethod = “fallback”),
hystrix 默认超时时间是 1000 毫秒,如果你后端的响应超过此时间,就会触发 断路器;
修改 hystrix 的默认超时时间:
@RequestMapping("/cloud/goodsHystrix")
@HystrixCommand(fallbackMethod = "fallback",
commandProperties={
@HystrixProperty(name="execution.timeout.enabled", value="true"),
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="5000")
})
public ResultObject goodsHystrix()
或者在配置文件进行配置:
ribbon.ReadTimeout=6000
ribbon.ConnectTimeout=3000
hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
这里有个坑需要注意一下:
如果 hystrix.command.default.execution.timeout.enabled为 true,则会有两个执行方法超时的配置,一个就是ribbon的 ReadTimeout,一个就是熔断器hystrix的 timeoutInMilliseconds, 此时谁的值小谁生效;
如果 hystrix.command.default.execution.timeout.enabled为 false,则熔断器不进行超时熔断,而是根据ribbon的 ReadTimeout抛出的异常而熔断,也就是取决于ribbon的 ConnectTimeout,配置的是请求服务的超时时间,除非服务找不到,或者网络原因,这个时间才会生效;
ribbon.ReadTimeout=6000
ribbon.ConnectTimeout=3000
本文介绍了如何在Spring Cloud中使用Hystrix实现断路器功能,包括添加依赖、启用断路器、设置超时时间以及如何通过配置文件调整超时策略。同时,注意了当Hystrix与Ribbon超时配置冲突时的行为解析。
848

被折叠的 条评论
为什么被折叠?



