1.熔断机制
![2c50df4f7a5a4a1b7416673f4257ddba.png](https://i-blog.csdnimg.cn/blog_migrate/1500d4fbd14ace03f6c2f262a5bc7400.png)
2.熔断
坐标
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
service层
@Service
//@CacheConfig(cacheNames = "item")
public class ItemService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "fallback",
commandProperties = {//默认 20 个;10s 内请求数大于 20 个时就启动熔断器,当请求符合熔断条件时将触发 getFallback()。
@HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value="10"),
//请求错误率大于 50%时就熔断,然后 for 循环发起请求,当请求符合熔断条件时将触发 getFallback()。
@HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value="50"),
//默认 5 秒;熔断多少秒后去尝试请求
@HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value="5000")
})
public List<Item> getItemList(){
return restTemplate.getForObject("http://feign-provider/item/list", List.class);
}
public List<Item> fallback(){
List<Item> list = new ArrayList<>();
list.add(new Item(1, "test"));
return list;
}
}
调用getItemlist方法发生异常时,当满足错误率大于50%同时10秒请求大于20个就会开启熔断机制,这时就会调用fallback方法返回托底数据,每5秒会尝试重新调用下getItemList()方法,发生异常继续开启熔断机制
启动器
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker//开启熔断器
public class EurekaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerApplication.class, args);
}
}
3.熔断参数
![f01e88ad82fde35a7fe1d3eedd4f9c6f.png](https://i-blog.csdnimg.cn/blog_migrate/6453c350ad8639e9ea152eae66142b47.jpeg)