熔断机制是应对雪崩效应的一种微服务链路保护机制,当扇出链路的某个微服务出错不可用或者响应时间太长时,会进行服务降级,进而熔断该节点微服务调用,快速返回错误的相应信息。
Spring Cloud中,熔断机制可以通过Hystrix实现,Hystrix可以监控微服务间调用的情况。当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制,熔断机制的注解是@HystrixCommand。
当启动熔断机制后,后续对该服务接口的调用不再经过网络,直接执行本地的默认方法,达到服务降级的效果。
经过了规定的时间窗口后,服务将从熔断状态恢复过来,再次接受调用方的远程调用。
官网原图:
以下是大致流程(画图工具做的,较为简陋)
service
//========================服务熔断=====================
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
})
public String paymentCircuitBreaker(Integer id){
if(id<0){
throw new RuntimeException("id<0");
}
String serialNumber = IdUtil.simpleUUID();
return Thread.currentThread().getName()+"\t"+"调用成功,流水号:"+serialNumber;
}
public String paymentCircuitBreaker_fallback(Integer id){
return "id<0"+":"+id;
}
controller
@RestController
public class PaymentController {
@Autowired
private PaymentService paymentService;
@GetMapping("/payment/hystrix/breaker/{id}")
public String paymentCircuitBreaker(@PathVariable Integer id){
return paymentService.paymentCircuitBreaker(id);
}
}
上述代码,当请求id小于0时,抛出异常,大于0时,请求正常。
效果:当我连续请求id等于负数的请求后,发现短暂时间内,请求id等于整数的发现服务仍然降级了,但是过了一会,请求整数id又成功了,说明服务熔断触发。
熔断触发图:
恢复:
hystrix配置属性主要在HystrixCommandProperties.class中有详细记载:
原文:https://www.cnblogs.com/wwjj4811/p/13622247.html