案例代码:https://gitee.com/menbbo/springclouddemo.git
Hystrix断路器
什么是hystrix?
Hystrix是一个用来处理分布式系统的延迟和容错的开源库,在分布式系统里,很多依赖会不可避免的调用失效,比如超时、异常。Hystrix能够保证一个依赖出现问题时,不会导致服务整体失效,避免级联故障,以提高分布式系统的弹性。
“断路器”本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控,向调用方法返回一个服务预期的,可处理的备选响应(fallback),而不是长时间的等待或是跑出异常,这样可以保证服务调用的线程不会长时间的被占用。不必要的占用,从而避免了故障在分布式系统中的蔓延。
Hystrix的功能
Hystrix的功能主要有:服务降级、服务熔断、服务限流以及接近实时的监控。
服务降级:服务降级是指在服务压力剧增时,根据当前业务的情况有选择性的对一些服务有策略的降级,减轻服务器的压力,保证核心任务的运行。
服务熔断:服务熔断是指由于某些原因使服务出现故障,为了防止整个系统故障,从而采取的一种保护措施,也称之为过载保护。
服务限流:服务限流是指对并发访问进行限速来保护系统。
监控:HystrixCommand和HystrixObservableCommand在执行时,会生成执行结果和运行指标,比如每秒执行的请求数和成功数。
springcloud关于hystrix的应用
(1)consumer模块中添加依赖
<dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-javanica</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-metrics-event-stream</artifactId> </dependency>
(2)consumer01模块中创建IndexApi接口
@FeignClient(value = "SEARCH") public interface IndexApi { @RequestMapping(value = "/index") public String index(); }
(3)该接口的具体的实现在producet01模块下的ProducerController中,此时使用@HystrixCommand(fallbackMethod = "index2")注解可实现服务熔断功能。即当index()方法出现异常时,可调用index2()进行处理。
@RestController public class ProducerController { @RequestMapping(value = "/index") @HystrixCommand(fallbackMethod = "index2")//熔断 调用fun2 public String index(){ int a= 1/0; //服务熔断 处理过程在服务端 ,服务降级处理逻辑在客户端。 String index = "producer01......."; System.out.println("producer01......."); return index; } public String index2(){ System.out.println("index2"); return "index2"; }
启动以上服务,访问localhost:8086/index可以看见访问了index2方法。
(4)在IndexApi接口中添加参数fallbackFactory = IndexApiHystrix.class
@FeignClient(value = "SEARCH",fallbackFactory = IndexApiHystrix.class) public interface IndexApi { @RequestMapping(value = "/index") public String index(); }
(5)服务降级实现,在consumer01模块中,创建IndexApiHystrix类实现FallbackFactory接口。
@Component public class IndexApiHystrix implements FallbackFactory { @Override public IndexApi create(Throwable throwable) { IndexApi indexApiHystrix = new IndexApi() { @Override public String index() { return "服务降级调用index方法"; } }; return indexApiHystrix ; }
(6)consumer01启动类,添加@EnableCircuitBreaker注解
@SpringBootApplication @EnableFeignClients //feign服务调用 @EnableDiscoveryClient @EnableCircuitBreaker public class Consumer01Application { public static void main(String[] args) { SpringApplication.run(Consumer01Application.class, args); } @Bean public ServletRegistrationBean hys(){ ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet()); servletRegistrationBean.addUrlMappings("/actuator/hystrix.stream"); return servletRegistrationBean; } }
注释掉ProducerController的注解 @HystrixCommand(fallbackMethod = "index2")启动服务,访问url得到结果: