1. Hystrix 断路器 概念
Hystrix是一个用于分布式系统的延迟和容错的开源库,在分布式系统中,许多依赖会不可避免的调用失败,例如超时,异常等,Hystrix能保证在一个依赖出现问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
- 为系统提供保护和控制
- 以进行快速失败,缩短延迟等待时间
- 提供失败回退(Fallback)和相对优雅的服务降级机制
- 提供有效的服务容错监控、报警和运维控制手段
1.1 配置依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
1.2 application.yml 配置
feign:
hystrix:
enabled: true #开启feign的熔断机制
1.3 启动类配置
只需要在启动类上加上@EnableCircuitBreaker注解即可,如下所示:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class ShopConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ShopConsumerApplication.class, args);
}
}
1.4 接口的编写
使用@FeignClient注解 name=“服务名” fallback=“降级服务调用接口”
例如: Service层中如果调取失败就走指定的降级类
@Service
@FeignClient(name = "ms-provider", fallback = TestServiceFellback.class)
public interface TicketService {
@RequestMapping("/test/test01")
public Object getAllTicket();
}
实现一个降级服务后的快速响应
@Component
public class TestServiceFellback implements TicketService {
@Override
public Object getAllTicket() {
return "熔断入口";
}
}
最终实现跳闸后的接口
2. Hystrix 监控
2.1 配置依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
2.2 启动类配置
在启动类上加上@EnableHystrixDashboard注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrixDashboard
public class ShopConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ShopConsumerApplication.class, args);
}
}
2.3 接口的编写(需要提供降级后走的服务)
编写一个config
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/actuator/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
2.4 访问Hystrix Dashboard
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nkRDqJyU-1570769816291)(467377DCD5FF4F60B14AA714576CBF24)]
在输入框中输入:http://locahost:8080 + 设定的地址 我的是 /actuator/hystrix.stream
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jwVKcQQV-1570769816293)(00A7C653C73D4C758BAE84860402D229)]
2.5 Hystrix 超时设置
如果有需求需要设置时间就在application.yml中配置
hystrix:
command:
default: #default全局有效,service id指定应用有效
execution:
timeout:
#如果enabled设置为false,则请求超时交给ribbon控制,为true,则超时作为熔断根据
enabled: true
isolation:
thread:
timeoutInMilliseconds: 50000 #断路器超时时间,默认1000ms