hystrix的使用
1 是什么
分布式系统下,服务之间都是相互依赖的,一个服务可能依赖多个服务,当某一个服务不可用时,请求线程被阻塞,当有大批量请求时,最终可能导致整个资源耗尽,无法继续对外提供服务,从而造成雪崩。
为了解决雪崩现象,使服务高可用、具有稳定性,我们的服务应当具有自我保护能力,当依赖服务不可用时,当前服务启动自我保护功能。Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力
2 怎么用
主程序添加注解@EnableCircuitBreaker
@EnableCircuitBreaker
@ComponentScan(basePackages = "com.xiaohou.springcloud")
@SpringBootApplication
public class UserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceProviderApplication.class, args);
}
2.1 熔断触发降级
2.1.1 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.1.2 创建访问层
@RestController
public class HystrixController {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(commandProperties = {
@HystrixProperty(name="circuitBreaker.enabled",value ="true"),
@HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "20"),
@HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "5000"),
@HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50")},fallbackMethod = "fallback")
@GetMapping("/hystrix/order/{num}")
public String queryOrder(@PathVariable("num")int num){
if(num%2==0){
return "正常访问";
}
//restTemplate默认有一个请求超时时间
return restTemplate.getForObject("http://localhost:8082/orders",String.class);
}
public String fallback(int num){
return "系统繁忙,请稍后重试";
}
}
说明:
circuitBreaker.enabled:开启熔断
circuitBreaker.requestVolumeThreshold:最小请求数,而不是最小失败请求数。举个例子如果值是20,那么如果在滚动窗口中只接收到19个请求(比如一个10秒的窗口),即便所有19个请求都失败了,熔断判断逻辑也不会被触发。
circuitBreaker.sleepWindowInMilliseconds:熔断时间
circuitBreaker.errorThresholdPercentage:失败率
10s之内,发起了20次请求,失败率超过50%。 熔断的恢复时间(熔断5s),从熔断开启
到后续5s之内的请求,都不会发起到远程服务端。
2.2 请求超时触发降级
在控制层增加方法,在方法上添加注解:
/**
* 请求超时触发降级
* @return
*/
@HystrixCommand(commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
},fallbackMethod ="timeoutFallback")
@GetMapping("/hystrix/timeout")
public String queryOrderTimeOut(){
return restTemplate.getForObject("http://localhost:8082/orders",String.class);
}
public String timeoutFallback(){
return "请求超时";
}
2.3 整合OpenFeign
- 服务方模块(order-service-api)定义接口,使用注解@FeignClient,定义回退类
@FeignClient(value = "order-service",fallback =OrderServiceFeignClient.OrderServiceFeignClientFallBack.class )
public interface OrderServiceFeignClient extends OrderService{
@GetMapping("/feign/orders")
String orders();
@Component
class OrderServiceFeignClientFallBack implements OrderServiceFeignClient{
public String orders() {
return "查询订单失败,请稍后重试";
}
public int insert(OrderDto dto) {
return -1;
}
}
}
在消费方添加依赖包order-service-api
<dependency>
<groupId>org.example</groupId>
<artifactId>order-service-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
消费方配置文件中开启feign的支持
feign:
hystrix:
enabled: true
在消费方主程序类
@EnableCircuitBreaker
@ComponentScan(basePackages = {"com.xiaohou.springcloud","com.xiaohou.springcloud.clients"})
@SpringBootApplication
@EnableFeignClients(basePackages = "com.xiaohou.springcloud")
public class UserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceProviderApplication.class, args);
}
}
2.5 资源隔离触发降级
Hystrix的资源隔离策略有两种,分别为:线程池和信号量。
线程池方式
1、 使用线程池隔离可以完全隔离第三方应用,请求线程可以快速放回。
2、 请求线程可以继续接受新的请求,如果出现问题线程池隔离是独立的不会影响其他应用。
3、 当失败的应用再次变得可用时,线程池将清理并可立即恢复,而不需要一个长时间的恢复。
4、 独立的线程池提高了并发性
缺点:
线程池隔离的主要缺点是它们增加计算开销(CPU)。每个命令的执行涉及到排队、调度和上 下文切换都是在一个单独的线程上运行的。
信号量
使用一个原子计数器(或信号量)来记录当前有多少个线程在运行,当请求进来时先判断计数 器的数值,若超过设置的最大线程个数则拒绝该请求,若不超过则通行,这时候计数器+1,请求返 回成功后计数器-1。
与线程池隔离最大不同在于执行依赖代码的线程依然是请求线程
tips:信号量的大小可以动态调整, 线程池大小不可以
参考链接:https://blog.csdn.net/qq_39380737/article/details/106310132
2.4整合dashbord
- 创建工程,引入spring-cloud-starter-netflix-hystrix-dashboard依赖,在主程序类上添加注解@EnableHystrixDashboard
@EnableHystrixDashboard
@SpringBootApplication
public class SpringCloudHystrixDashbord9092Application {
public static void main(String[] args) {
SpringApplication.run(SpringCloudHystrixDashbord9092Application.class, args);
}
}
-
配置工程端口,我的是9092,。
-
被监控工程,配置文件中打开hystrix.stream端点,
management:
endpoints:
web:
exposure:
include: refresh,hystrix.stream
输入网址:
http://localhost:9092/hystrix
进入之后面板:
注: 仪表盘功能如果出现Unable to connect to Command Metric Stream.的异常解决方案
在dashboard工程加入如下配置即可
hystrix:
dashboard:
proxy-stream-allow-list: "localhost"