断路器的作用:
当请求因为自身原因或网络原因,无法正常返回时,正常的情况下需等到访问超时客户才会得到回复,此时如果请求过多,超过Servlet容器线程资源,会导致服务瘫痪。而断路器能很好的解决这一问题,在出现此情况时,断路器会立即按开发人员具体实现作出返回,很好的减少了请求因错误而引发的线程占用时间。
依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在Spring Boot启动类上增加@EnableHystrix注解,开启Hystrix断路器
@EnableEurekaClient
@SpringBootApplication
@EnableHystrix
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
/**
* @return
* @LoadBalanced注解表明RestTemplate开启负载均衡的功能
*/
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
在需要断路器的service方法上注明异常处理方式:
* 当hiService方法中发送错误时,则会执行fallbackMethod回调
*
* @param name
* @return
*/
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name=" + name, String.class);
}
private String hiError(String name) {
return "sorry,error!";
}