标签:products LTP 方法 src spring efault pre 使用 打开
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//设置熔断
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //最小请求数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //10秒
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") //滚动时间10秒钟,有7次发生错误。断路器被设置为打开状态。
一、HystrixController .java
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
//@HystrixCommand(fallbackMethod = "fallback")
//2、超时设置
/*@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000") //超时时间设置为3秒
})*/
//3.
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//设置熔断
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
})
@GetMapping("/getProductInfoList")
public String getProductInfoList(@RequestParam("number") Integer number){
if(number % 2 == 0){
return "success";
}
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForObject("http://127.0.0.1:8091/product/listForOrder", Arrays.asList("157875196366160022"),String.class);
}
private String fallback(){
return "太拥挤了,请稍后再试~~";
}
private String defaultFallback(){
return "默认提示:太拥挤了,请稍后再试~~";
}
}
Product工程中的方法
@PostMapping("/listForOrder")
public List<ProductInfo> listForOrder(@RequestBody List<String> productIdList){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return productService.findList(productIdList);
}
调用:
number为2时成功返回

number为1时,触发熔断

熔断:
不停的调用 http://localhost:8081/getProductInfoList?number=1 。
然后调用http://localhost:8081/getProductInfoList?number=2, 也出现拥挤提示

然后再次调用http://localhost:8081/getProductInfoList?number=2 就正常了。
二、使用配置,设置过期时间
设置超时时间为1秒
spring:
application:
name: order
redis:
host: 47.98.47.120
port: 6379
cloud:
config:
discovery:
enabled: true
service-id: CONFIG
profile: test
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000
接口配置
@HystrixCommand
@GetMapping("/getProductInfoList")
public String getProductInfoList(@RequestParam("number") Integer number){
if(number % 2 == 0){
return "success";
}
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForObject("http://127.0.0.1:8091/product/listForOrder", Arrays.asList("157875196366160022"),String.class);
}
三、为单个方法配置超时时间

给getProductInfoList设置超时时间为3秒
标签:products LTP 方法 src spring efault pre 使用 打开
原文地址:https://www.cnblogs.com/linlf03/p/10398466.html