微服务组件:服务容错hystrix
1. hystrix介绍
Hystrix是Netflix的一款开源组件,它通过熔断模式、隔离模式、回退(fallback)和限流等机制对服务进行弹性容错保护,保证系统的稳定性。
2. hystrix
3. hystrix使用
3-1 启动客户端
在spring boot启动Application类上,添加注解启动对hystrix的监控
@EnableCircuitBreaker
依赖调用逻辑
@Service public class MengkaHystrixService { @HystrixCommand(fallbackMethod = "defaultFallbackMethod") public String alwaysFailsMethod() { throw new RuntimeException("Bad stuff has happened!"); } @HystrixCommand(fallbackMethod = "failingFallbackMethod") public String alwaysFailsDownTheChainMethod() { throw new RuntimeException("Bad stuff continues to happen!"); } @HystrixCommand(fallbackMethod = "defaultFallbackMethod") public String longRunningMethod() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } return "this method takes too long!"; } private String defaultFallbackMethod() { return "success"; } @HystrixCommand(fallbackMethod = "secondFallbackMethod") private String failingFallbackMethod() { throw new RuntimeException("Bad stuff has happened!"); } private String secondFallbackMethod() { return "more success"; } }
访问:
http://127.0.0.1:8073/hystrix.stream
已经可以获取hystrix依赖调用统计数据,说明启动成功。
3-2 启动hystrix-dashboard
maven依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
启动hystrix-dashboard
@SpringBootApplication @EnableHystrixDashboard public class HystrixDashboardApplication { public static void main(String[] args) { new SpringApplicationBuilder(HystrixDashboardApplication.class).web(true).run(args); } }
访问页面:
http://localhost:8030/hystrix.stream
3-3 添加应用依赖调用地址
添加http://127.0.0.1:8073/hystrix.stream,进入monitor stream
3-4 测试接口降级
alwaysFailsDownTheChainMethod>>failingFallbackMethod>>secondFallbackMethod
3-5 测试接口超时
longRunningMethod>>defaultFallbackMethod