Hystrix 服务提供方-服务降级(Hystrix service provider – service degradation)

  • 首先导入 Hystrix Maven 依赖
<!--新增hystrix-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  • 在可能会超时或出现异常的方法上加 @HystrixCommand 注解,并添加回调方法
//超时降级演示
@HystrixCommand(fallbackMethod = "payment_TimeoutHandler", commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000") //5秒钟以内就是正常的业务逻辑
})
@GetMapping("/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable("id") Integer id) {
    String result = paymentService.payment_Timeout(id);
    log.info("*******result:" + result);
    return result;
}

// 方法名与 @HystrixCommand 声明的方法名一致
public String payment_TimeoutHandler(Integer id) {
        return "线程池:" + Thread.currentThread().getName() + " payment_TimeoutHandler,系统繁忙,请稍后再试\t o(╥﹏╥)o ";
    }
  • 在主启动类上添加 @EnableCircuitBreaker 方法
————————
  • 首先导入 Hystrix Maven 依赖
<!--新增hystrix-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  • Annotate @ hystrixcommand on methods that may time out or have exceptions, and add callback methods
//超时降级演示
@HystrixCommand(fallbackMethod = "payment_TimeoutHandler", commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000") //5秒钟以内就是正常的业务逻辑
})
@GetMapping("/hystrix/timeout/{id}")
public String paymentInfo_Timeout(@PathVariable("id") Integer id) {
    String result = paymentService.payment_Timeout(id);
    log.info("*******result:" + result);
    return result;
}

// 方法名与 @HystrixCommand 声明的方法名一致
public String payment_TimeoutHandler(Integer id) {
        return "线程池:" + Thread.currentThread().getName() + " payment_TimeoutHandler,系统繁忙,请稍后再试\t o(╥﹏╥)o ";
    }
  • 在主启动类上添加 @EnableCircuitBreaker 方法