- POM文件中添加
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
- 主启动类添加
@EnableCircuitBreaker
或者@EnableHystrix
- 使用一:在需要服务降级的接口上添加
@HystrixCommand
指定fallbackMethod
方法
@GetMapping("/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOut_fallback",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000") //3秒钟以内就是正常的业务逻辑
})
public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
int a = 10/id;
int b = 5; //方法执行五秒,超时
try {
TimeUnit.SECONDS.sleep(b);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池:"+Thread.currentThread().getName()+"----"+a+"";
}
public String paymentInfo_TimeOut_fallback(Integer id){
return "线程池:"+Thread.currentThread().getName()+"我来兜底了";
}
- 使用二 Feign使用Hystrix
在@FeignClient上添加fallback
属性指定兜底的类,这个类实现这个接口,实现的方法就是兜底的方法
@Service
@FeignClient(value = "cloud-payment-service",fallback = PaymentServiceFallback.class)
public interface PaymentService {
@GetMapping("/payment/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
@Service
class PaymentServiceFallback implements PaymentService{
@Override
public String paymentInfo_TimeOut(Integer id) {
return "兜底方法----paymentInfo_TimeOut"+"对方服务异常";
}
}
重点:要想使用这种方式,必须在配置文件中添加
#feign使用hystrix开启服务熔断
feign:
hystrix:
enabled: true #如果处理自身的容错就开启。
- 方式三
@DefaultProperties
设置全局兜底方法
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod") //全局的
public class PaymentController {
@GetMapping("/payment/hystrix/timeout/{id}")
@HystrixCommand //这个注解不能少
public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
int a = 10/id;
return "线程池:"+Thread.currentThread().getName()+"----"+a+"";
}
//必须是无参方法
public String payment_Global_FallbackMethod(){
return "线程池:"+Thread.currentThread().getName()+"我来兜底了,我是全局兜底";
}
}
注意这里的全局兜底方法不能有参数