引入hystrix及使用
在pom中增加:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
然后在启动类上加上:
@EnableCircuitBreaker
降级服务的写法,就是利用注释如下这种写法即可:
@HystrixCommand(fallbackMethod = "fallback")
完整代码,如果服务:
@RestController
public class HystrixController {
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping("/getProductInfoList")
public String getProductInfoList() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForObject("http://127.0.0.1:8082/product/listForOrder", Arrays.asList("157875196366160022"), String.class);
}
private String fallback() {
return "太拥挤了,请稍后再试~~";
}
}
另外一种设置方式,通过默认的DefaultProperties进行配置,这样会调用默认的defaultFallback:
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
@HystrixCommand(/*fallbackMethod = "fallback"*/)
@GetMapping("/getProductInfoList")
public String getProductInfoList() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForObject("http://127.0.0.1:8082/product/listForOrder", Arrays.asList("157875196366160022"), String.class);
}
private String fallback() {
return "太拥挤了,请稍后再试~~";
}
private String defaultFallback() {
return "默认提示:太拥挤了,请稍后再试~~";
}
}
设置超时时间:
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
// @HystrixCommand(/*fallbackMethod = "fallback"*/)
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
@GetMapping("/getProductInfoList")
public String getProductInfoList() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForObject("http://127.0.0.1:8082/product/listForOrder", Arrays.asList("157875196366160022"), String.class);
}
private String fallback() {
return "太拥挤了,请稍后再试~~";
}
private String defaultFallback() {
return "默认提示:太拥挤了,请稍后再试~~";
}
}