Hystrix的实现

本文介绍了如何在Spring Cloud中使用Hystrix实现断路器功能,包括添加依赖、启用断路器、设置超时时间以及如何通过配置文件调整超时策略。同时,注意了当Hystrix与Ribbon超时配置冲突时的行为解析。

第一步: 添加依赖

<!-- 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.enabledtrue,则会有两个执行方法超时的配置,一个就是ribbon的 ReadTimeout,一个就是熔断器hystrix的 timeoutInMilliseconds, 此时谁的值小谁生效;

如果 hystrix.command.default.execution.timeout.enabledfalse,则熔断器不进行超时熔断,而是根据ribbon的 ReadTimeout抛出的异常而熔断,也就是取决于ribbon的 ConnectTimeout,配置的是请求服务的超时时间,除非服务找不到,或者网络原因,这个时间才会生效;

ribbon.ReadTimeout=6000
ribbon.ConnectTimeout=3000
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值