1:上pom
<!--新增hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2:主启动类上注解不能少@EnableCircuitBreaker,开启hystrix服务
2:首先在需要用到的服务方法上添加如下注解
以下注解为在10s中,请求了10次,其中失败率达到了60%,加上之后在错误率达到了60后,就会访问兜底方法,下次正确的访问也不一定会访问成功,需要提高以下成功率后才会恢复访问
@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"),// 失败率达到多少后跳闸
// @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")// 超时处理
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
if (id < 0) {
throw new RuntimeException("**********--id不能为负数" + id);
}
String uuid = IdUtil.simpleUUID();
return Thread.currentThread().getName() + "----" + uuid;
}
//兜底方法
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
return "id不能为负数" + id;
}