SpringCloud Hystrix服务降级
包含内容: 源码,全套工具
作者QQ1420527913
由于SpringCloud提供的服务以微服务形式向外提供接口服务, 微服务假设有三个服务, A,B,C, A调用B的接口, B调用C的接口, 如果C接口有问题,那么A将无法对外提供正常服务, 从而服务产生雪崩现象, 为了更友好进行交互,在调用方可以使用Hystrix提供的服务降级功能, 也就是当服务不可用时,默认调用本地的一个方法
项目对应的实例代码可以通过【下载实例】按钮获取
开发工具: IntelliJ IDEA2017, JDK1.8, Maven 3.0.2
【项目包含内容】(见下图):
hystrix: 服务调用方
product: 服务提供方

1. 使用 IntelliJ IDEA打开 hystrix 和 product 二个工程, 并且启动二个工程
2. hystrix代码如下:
当使用调用方调用产生异常和超时,会发生服务降级即调用 defaultFallback, fallback函数
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
@GetMapping("/getProductInfoList")
public String getProductInfoList(){
RestTemplate restTemplate = new RestTemplate();
String str = (String)restTemplate.postForObject("http://127.0.0.1:8005/productInfoList", null, String.class);
return str;
}
@HystrixCommand
@GetMapping("/getDefaultHystrixProductInfoList")
public String getDefaultProductInfoList(){
RestTemplate restTemplate = new RestTemplate();
String str = (String)restTemplate.postForObject("http://127.0.0.1:8005/productInfoList", null, String.class);
return str;
}
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping("/getHystrixProductInfoList")
public String getHystrixProductInfoList(){
RestTemplate restTemplate = new RestTemplate();
String str = (String)restTemplate.postForObject("http://127.0.0.1:8005/productInfoList", null, String.class);
return str;
}
@HystrixCommand(commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="3000")
})
@GetMapping("/getHystrixTimeoutProductInfoList")
public String getHystrixTimeoutProductInfoList(){
RestTemplate restTemplate = new RestTemplate();
String str = (String)restTemplate.postForObject("http://127.0.0.1:8005/productInfoList", null, String.class);
return str;
}
private String fallback(){
return "太拥挤了,请稍后再试~";
}
private String defaultFallback(){
return "默认提示: 太拥挤了, 请稍后再试~";
}
}3. product代码如下(提供了一个http post服务)
@PostMapping("/productInfoList")
public String productInfoList(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
return "这是产品信息";
}