Hystrix服务降级:
当系统的方法调用时,发生错误或系统宕机或网络卡顿调用失败时,系统可以使用其他方法来进行调用来防止直接将系统回传直接发给调用者。可以使代码更加健壮
调用方式
在系统服务提供端(provicer)
首先在pom端添加坐标
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
其次在main方法头部添加注解@EnableCircuitBreaker
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class,args);
}
}
在上方使用了eureka为注册中心所以一并加入
其次在具体的方法上方添加注解@HystrixCommand
@HystrixCommand(fallbackMethod = "paymentInfo_timeoutHandler",HystrixCommand= {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
public String paymentInfo_timeout(Integer id)
这里为了使方法运行出错,可以在@HystrixCommand注解中的HystrixCommand属性中添加@HystrixProperty注解,"execution.isolation.thread.timeoutInMilliseconds"可以修改方法运行时间,超过设定就报超时错误,上方设定为3秒
而其中的fallbackMethod 是填写发生错误后调用的方法的属性名,"paymentInfo_timeoutHandler"为调用方法名
public String paymentInfo_timeoutHandler(Integer id){
return "发生了服务降级,线程为:"+Thread.currentThread().getName()+"\t"+"输入id为:"+id+"\t"+"原本方法为:paymentInfo_timeout";
}
在系统服务用户端(consumer)
其他不变,在main方法中的@EnableCircuitBreaker注解要改为@EnableHystrix
@SpringBootApplication
@EnableFeignClients
@EnableHystrix
public class OrderHystrixMain80
为了减少系统代码量,减少系统代码耦合,在一般的错误中应使用全局降级,就是所有发生错误的方法调用一个服务降级方法。
这样可以在文件头部添加一个注解**@DefaultProperties**,而具体的方法上只用写一个**@HystrixCommand**注解即可
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "global_handler")
public class PaymentHystrixController
@HystrixCommand
@GetMapping(value = "/payment/consumer/hystrix/ok/get/{id}")
public String payment_ok(@PathVariable(value="id") Integer id)
而当你consumer端使用的是Feign时,可以使用feign的方法对调用的所有方法写一个对应的fallback
在系统配置application.yml或application.properties添加
feign:
hystrix:
enabled: true
而对应的PaymentHystrixService接口的实现类PaymentHystrixFallbackService当中的方法就是调用微服务失败后的服务降级方法
@FeignClient(value = "CLOUD-PAYMENT-HYSTRIX-SERVICE",fallback = PaymentHystrixFallbackService.class)
public interface PaymentHystrixService{
@GetMapping(value = "/payment/hystrix/ok/{id}")
public String paymentInfo_ok(@PathVariable(value="id") Integer id);
@GetMapping(value = "/payment/hystrix/timeout/{id}")
public String paymentInfo_timeout(@PathVariable(value="id") Integer id);}
注意在创建的新文件头部要加@Component
@Component
public class PaymentHystrixFallbackService implements PaymentHystrixService {
@Override
public String paymentInfo_ok(Integer id) {
return "thih is paymentInfo_ok method fallback";
}
@Override
public String paymentInfo_timeout(Integer id) {
return "thih is paymentInfo_timeout method fallback";
}
}
注意如果同时运用@Feign当中的全局fallback和
@DefaultProperties(defaultFallback = “global_handler”)时
方法名上有@HystrixCommand的会使用DefaultProperties当中的方法,而没有的会使用Feign当中的方法