Hystrix服务降级
使用方法
- pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 启动类
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain.class,args);
}
}
- 具体业务添加降级处理方法 @HystrixCommand中fallbackMethod方法
@Override
@HystrixCommand(fallbackMethod = "paymentInfoTimeoutMethod",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
public String paymentInfoTimeout(Integer id) {
int timeNumber = 5;
//暂停三秒
try {
TimeUnit.SECONDS.sleep(timeNumber);
}catch (InterruptedException e) {
e.printStackTrace();
}
return Thread.currentThread().getName()+"paymentInfoTimeout,id"+"\t"+id;
}
public String paymentInfoTimeoutMethod(Integer id){
return Thread.currentThread().getName()+"paymentInfoTimeoutMethod,id:"+"\t"+id;
}
代码缺点
- 每个业务都有一个对应降级处理方法,代码膨胀
- 和业务逻辑混在一起,代码耦合性高
解决方法
-
配置通用的fallback方法
利用以下注解:
@DefaultProperties(defaultFallback = “payment_global_fallbackMethod”)+ @HystrixCommand
实现除了个别重要核心业务专属配置降级处理方法外,其他普通的均通过@DefaultProperties中的defaultFallback方法处理
好处:将通用和独享分开,避免了代码膨胀,合理减少了代码量 -
整合feign,利用feign调用其他服务接口
- 在yml中开启feign对hystrix的支持
feign: hystrix: enabled: true #在feign中开启hystrix
- 定义fallback处理类
@Component @FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallBackServiceImpl.class) public interface PaymentService { @GetMapping("/payment/hystrix/ok/{id}") public String paymentInfoOk(@PathVariable(value = "id")Integer id); @GetMapping("/payment/hystrix/timeout/{id}") public String paymentInfoTimeout(@PathVariable(value="id")Integer id); }
- 实现feign调用接口服务类,在客户端自己实现服务降级处理
@Component public class PaymentFallBackServiceImpl implements PaymentService { @Override public String paymentInfoOk(Integer id) { return "服务降级:解耦处理,交给feign调用其他服务接口进行处理,paymentInfoOk"; } @Override public String paymentInfoTimeout(Integer id) { return "服务降级:解耦处理,交给feign调用其他服务接口进行处理,paymentInfoTimeout"; } }
好处:客户端自己做了服务降级处理,若此时其他服务端不可用或者宕机,会给客户端提示信息,从而不会挂起耗死服务器