熔断和降级的配置基本差不多,不同之处就在于使用HystrixCommand注解
熔断就是在此注解中通过配置commandProperties完成。
例
在服务端配置熔断
在Service层,当然也可以在controller层配置
service层
@HystrixCommand(fallbackMethod = "breakerFallback", commandProperties = {
//开启熔断
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
//熔断触发的最小个数/10s,默认值20
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
//熔断多少秒后去尝试请求,默认值5000
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),
//失败率达到多少百分比后熔断,默认值50
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String breaker(int id){
log.info("providerService--->{}",id);
if(id==404){
throw new RuntimeException("模拟熔断错误");
}
return "id:"+id+"--->正常业务";
}
public String breakerFallback(int id){
return "id:"+id+"--->熔断处理";
}
controller层
@RestController
@RequestMapping("user")
@Slf4j
@DefaultProperties(defaultFallback = "timeOutMethod")
public class UserControllerProvider {
@Autowired
UserService userService;
@RequestMapping("Breaker/{id}")
public String CircuitBreaker(@PathVariable("id") Integer id) {
log.info("CircuitBreaker()---> 执行");
return userService.breaker(id);
}
}
在客户端调用服务端暴露的接口
@RestController
@RequestMapping("user")
@Slf4j
public class UserControllerComsumer {
@Autowired
UserService userService;
@RequestMapping("Breaker/{id}")
public String circuitBreaker(@PathVariable("id") int id){
log.info("UserControllerComsumer-circuitBreaker->{}",id);
/*if(id==404)
throw new RuntimeException("消费者端降级");*/
return userService.CircuitBreaker(id);
}
}
浏览器中测试:在10秒内请求10次如果有百分之六十服务端都是返回的降级方法信息,那么就会开启断路器,不管是正确还是错误请求都会出发降级。
访问时路径携带404服务端就会抛出错误
public String breaker(int id){
log.info("providerService--->{}",id);
if(id==404){
throw new RuntimeException("模拟熔断错误");
}
return "id:"+id+"--->正常业务";
}
正常情况:
携带参数404,短时间内快速请求多次触发配置的断路。即使携带参数为1服务端也会触发降级