1、解释
2、测试断路器的工作状态
为了能够精确控制请求的成功或失败,我们在 shop_service_product 的调用业务中加入一段逻辑:
/**
* 使用注解配置熔断保护
* fallbackmethod : 配置熔断之后的降级方法
*/
@HystrixCommand(fallbackMethod = "orderFallBack")
@RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
public Product findById(@PathVariable Long id) {
if(id != 1) {
throw new RuntimeException("服务器异常");
}
return restTemplate.getForObject("http://service-product/product/1",Product.class);
}
这样如果参数是id为1,一定失败,其它情况都成功。
我们准备两个请求窗口:
一个请求:http://localhost:8080/consumer/1,注定失败
一个请求:http://localhost:8080/consumer/2,肯定成功
熔断器的默认触发阈值是20次请求,不好触发。休眠时间时5秒,时间太短,不易观察,为了测试方
便,我们可以通过配置修改熔断策略:circuitBreaker以下是熔断策略
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000 #默认的连接超时时间1秒,若1秒没有返回数据,自动的触发降级逻辑
circuitBreaker:
enabled: true
requestVolumeThreshold: 5
errorThresholdPercentage: 10
sleepWindowInMilliseconds: 10000
解读:
requestVolumeThreshold:触发熔断的最小请求次数,默认20
errorThresholdPercentage:触发熔断的失败请求最小占比,默认50%
sleepWindowInMilliseconds:熔断多少秒后去尝试请求
当我们疯狂访问id为1的请求时(超过10次),就会触发熔断。断路器会端口,一切请求都会被降级处
理。
此时你访问id为2的请求,会发现返回的也是失败,而且失败时间很短,只有20毫秒左右: