五 服务熔断
1、熔断是什么?
熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇形链路的某个微服务出错不可用或者响应、时间太长时,会进行服务的降级,从而熔断该节点微服务的调用,快速返回错误的响应信息。
当检测到该节点微服务调用响应正常后,恢复调用链路
在Spring Cloud框架中。熔断机制通过Hystrix实现。Hystrix会监控微服务之间调用的状况,
当失败的调用到一定阈值时,(缺省是5秒内调用20次失败,就会启动熔断机制)
熔断机制的注解是@HystrixCommand
2、如何配置熔断
① 找到服务提供者 cloud-provider-hystrix-payment8001
对 PaymentService 添加如下代码
//服务熔断
// 在时间窗口期10秒内,如果10次请求有6次是失败的,就会进行服务熔断
@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(@PathVariable("id") Integer id)
{
if(id < 0)
{
throw new RuntimeException("******id 不能负数");
}
String serialNumber = IdUtil.simpleUUID();
return Thread.currentThread().getName()+"\t"+"调用成功,流水号: " + serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
{
return "id 不能负数,请稍后再试,/(ㄒoㄒ)/~~ id: " +id;
}
②、controller就是正常的调用服务熔断的代码
// 服务熔断测试
@GetMapping("/payment/hystrix/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id) throws InterruptedException {
String result = paymentService.paymentCircuitBreaker(id);
return result;
}
③、测试:当10秒内,10次请求有6次是失败的话,就会进行熔断,此时,即使是正确的请求也会返回fullback
访问上述请求访问十次,然后切成正确请求,依旧返回fullback,证明此时服务是熔断的
最后继续发送正确请求,由于时间窗口期内,错误请求的次数降低,服务恢复链路