船新版本:
在消费者controller的方法上添加
注解
当提供服务的生产者出故障(例如关掉它),默认超时时间是1000毫秒,过了这个时间就触发熔断器,消费者无法访问生产者就返回error
添加 hystrix 起步依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>
主程序添加 @EnableCircuitBreaker 启用 hystrix 断路器
启动断路器,断路器提供两个核心功能:
- 降级,超时、出错、不可到达时,对服务降级,返回错误信息或者是缓存数据
- 熔断,当服务压力过大,错误比例过多时,熔断所有请求,所有请求直接降级
可以使用
@SpringCloudApplication注解代替三个注解
RibbonController 中添加降级方法
为每个方法添加降级方法,例如
getItems()添加降级方法getItemsFB()- 添加
@HystrixCommand注解,指定降级方法名 @GetMapping("/item-service/{orderId}")@HystrixCommand(fallbackMethod = "getItemsFB") //指定降级方法的方法名public JsonResult<List<Item>> getItems(@PathVariable String orderId) {return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);}
hystrix 超时设置
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix等待超时后, 会执行降级代码, 快速向客户端返回降级结果, 默认超时时间是1000毫秒
为了测试 hystrix 降级,我们把 hystrix 等待超时设置得非常小(500毫秒)
此设置一般应大于 ribbon 的重试超时时长,例如 10 秒
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 500




