本文共 4600 字,大约阅读时间需要 15 分钟。
熔断类型:
断路器开启或关闭的条件:
断路器打开之后:
恢复主逻辑:
所有配置:
依赖:
cloud2020 pers.zhang.springcloud 1.0-SNAPSHOT 4.0.0 cloud-provider-hystrix-payment8001 org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator pers.zhang.springcloud cloud-api-commons ${project.version} org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test
配置:application.yml
server: port: 8001spring: application: name: cloud-provider-hystrix-paymenteureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://eureka7001.com:7001/eureka #defaultZone: http://eureka7001.com:7001/eureka,http://wureka7002.com:7002/eureka
Service:
@Servicepublic class PaymentService { //服务熔断 @HystrixCommand(fallbackMethod = "paymentCircuitBreeaker_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 paymentCircuitBreeaker(@PathVariable("id") Integer id) { if (id < 0) { throw new RuntimeException("*******id 不能为负数"); } String serialNumber = IdUtil.simpleUUID(); return Thread.currentThread().getName() + "\t" + "调用成功,流水号:" + serialNumber; } public String paymentCircuitBreeaker_fallback(@PathVariable("id") Integer id) { return "id 不能为负数,请稍后再试。 id:" + id; }}
Controller:
@RestController@Slf4jpublic class PaymentController { @Resource PaymentService paymentService; //服务熔断 @GetMapping("/payment/circuit/{id}") public String paymentCircuitBreaker(@PathVariable("id") Integer id) { String result = paymentService.paymentCircuitBreeaker(id); log.info("****result: " + result); return result; }}
启动类:
@SpringBootApplication@EnableEurekaClient@EnableCircuitBreaker//开启熔断public class PaymentHystrixMain8001 { public static void main(String[] args) { SpringApplication.run(PaymentHystrixMain8001.class, args); }}
测试:
启动Eureka,和8001模块:
访问:localhost:8001/payment/circuit/33
,id为正数,成功
localhost:8001/payment/circuit/-3
:id为负数,失败 10秒内,快速调用id为负数的请求(最少6次),然后再调用id为正数的请求:失败,服务已经熔断
等待一会(默认空窗期5秒),再调用id为正的请求:成功,已经恢复调用链路