hystrix熔断器、仪表盘、健康检查功能使用文档,教程非常详细,傻瓜式操作

  • hystrix熔断器的使用
  • 添加依赖
  1. <dependency>  
  2.         <groupId>org.springframework.cloud</groupId>  
  3.         <artifactId>spring-cloud-starter-openfeign</artifactId>  
  4.     </dependency>  
  5.     <dependency>  
  6.         <groupId>org.springframework.cloud</groupId>  
  7.         <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>  
  8.  </dependency>  
  9. yml配置
  1. #设置Feign的配置  
  2. feign:  
  3.   hystrix:  
  4.     # 开启Hystrix,否则@FeignClient中的fallbackFactory配置不起作用。  
  5.     enabled: true  
  6.   
  7. #-----------------Hystrix配置-----------------------  
  8. hystrix:  
  9.   command:  
  10.     default:  
  11.       metrics:  
  12.         rollingStats:  
  13.           #设置滚动时间窗为5秒  
  14.           timeInMilliseconds: 5000  
  15.       execution:  
  16.         isolation:  
  17.           thread:  
  18.             # 设置命令执行的默认超时时间,单位毫秒  
  19.             timeoutInMilliseconds: 10000  
  20.         timeout:  
  21.           # 是否启用超时,如果不启用上面的值也不用配置。  
  22.           enabled: true  
  23.       circuitBreaker:  
  24.         # 是否启用断路器  
  25.         enabled: true  
  26.         # 单位时间内请求的总量需要达到阈值  
  27.         requestVolumeThreshold: 2  
  28.         # 错误率阈值,当错误率超过这个值,断路器打开  
  29.         errorThresholdPercentage: 50  
  30.         # 断路器打开后,多久后尝试恢复服务  
  31.         sleepWindowInMilliseconds: 10000  
  32.     # 开启Hystrix Dashboard  
  33.   dashboard:  
  34.     proxyStreamAllowList: localhost  
  35. enabled: true  

注:requestVolumeThreshold单位时间内请求的总量需要达到阈值,换句话说,假如某个窗口期内的请求总数都不到该配置值,那么断路器连发生的资格都没有。例如,如果值是20,那么如果在滚动窗口中只接收到19个请求(比如一个10秒的窗口),即便所有19个请求都失败了,熔断判断逻辑也不会被触发。测试时可以设置小一些,这样更容易被测出。

errorThresholdPercentage 该属性表示熔断触发条件,即触发熔断时错误百分比。一旦打到这个触发比例,断路器就进入“打开”状态,但前提是,需要整体的请求流量能够满足设置的容量。此配置项默认值是 50,即窗口时间内超过 50% 的请求失败后会打开熔断器将后续请求快速失败。

sleepWindowInMilliseconds可以理解为一个触发断路器的周期时间值,此配置项指定了熔断器打开后经过多长时间允许一次请求尝试执行,测试时可以设置大些,这样更容易被测出。

  1. 启动类添加注解

   启动类添加@EnableHystrix 注解

  1. FallbackFactory降级处理类
  1. @FeignClient(name = "imGateWayClientFeign",  
  2.         url = "${im-gateway.url}",  
  3.         fallbackFactory = ImGateWayClientFallbackFactory.class)  
  4. public interface ImGateWayClientFeign {  
  5.     @PostMapping("/handleEvent")  
  6.     CommonResult<Boolean> handleEvent(@Valid @RequestBody ImEventMessage imMessage);  
  7. }  

  1. @Slf4j  
  2. @Component  
  3. public class ImGateWayClientFallbackFactory implements FallbackFactory<ImGateWayClientFeign> {  
  4.     @Override  
  5.     public ImGateWayClientFeign create(Throwable throwable) {  
  6.         return new ImGateWayClientFeign() {  
  7.             @Override  
  8.             public CommonResult<Boolean> handleEvent(ImEventMessage imMessage) {  
  9.                 log.error("handleEvent error imMessage:{}", JSON.toJSONString(imMessage));  
  10.                 log.error(throwable.getMessage());  
  11.                 return CommonResult.fail(ResultCode.COMMON_FAIL.getCode(), ResultCode.COMMON_FAIL.getMessage());  
  12.             }  
  13.         };  
  14.     }  

注:在配置上方信息后,如果没有添加@Component,会启动失败,异常消息主要如下:

  1. Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'imProcessServiceImpl': Unsatisfied dependency expressed through field 'imGateWayClientFeign'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'imbridgeserver.sessionmanage.clients.ImGateWayClientFeign': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: No fallbackFactory instance of type class imbridgeserver.sessionmanage.clients.falllback.ImGateWayClientFallbackFactory found for feign client imGateWayClientFeign  

  1. 客户端测试方法(抛出异常)
  1.     @PostMapping("/handleEvent")  
  2.     public CommonResult<Boolean> handleEvent(@Valid @RequestBody ImEventMessage imMessage) {  
  3.         if(imMessage.getCid().equals("111")){  
  4.             throw new RuntimeException("测试异常");  
  5.         }  
  6.     }  
  7. }  
  1. Apifox测试

传参时cid传“111”,客户端会响应 “调用网关服务失败”。此时失败异常数+1。

如此重复3次调用(次数根据阈值设定来尝试),第四次修改成正确的cid,此时应响应“调用成功”,但仍然返回 “调用网关服务失败”。说明 触发了熔断,不再调用客户端,直接返回异常。 10秒后(根据设定恢复时间)再次请求,客户端响应“调用成功”

  • Hystrix Dashboard仪表盘的使用
  1. 添加依赖
  1. <dependency>  
  2.       <groupId>org.springframework.cloud</groupId>  
  3.      <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
  4.  </dependency>  
  5.  <dependency>  
  6.       <groupId>org.springframework.boot</groupId>  
  7.       <artifactId>spring-boot-starter-actuator</artifactId>  
  8.  </dependency>  
  1. yml配置

    # 开启Hystrix Dashboard,在hystrix配置基础下可以增加如下配置。

  1. dashboard:  
  2.   proxyStreamAllowList: localhost  
  3.   enabled: true  

注:proxyStreamAllowList: localhost如果不添加,监控页面也会显示:Unable to connect to Command Metric Stream. 

访问本地服务会出现下发情况。控制台会出现异常,异常信息如下。

  1. 2024-10-15 20:59:00.933 [http-nio-8081-exec-5] [] WARN  o.s.c.n.h.d.HystrixDashboardConfiguration$ProxyStreamServlet - Origin parameter: http://localhost:8081/ccti/im/bridge/actuator/hystrix.stream is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.

  

  1. 启动类添加注解

启动类添加注解@EnableHystrixDashboard

  1. 添加配置类
  1.  @Configuration  
  2. public class HystrixServletDefinitions {  
  3.     @Bean  
  4.     public ServletRegistrationBean getServlet() {  
  5.         HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();  
  6.         ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);  
  7.         registrationBean.setLoadOnStartup(1);  
  8.         registrationBean.addUrlMappings("/actuator/hystrix.stream");  
  9.         registrationBean.setName("HystrixMetricsStreamServlet");  
  10.         return registrationBean;  
  11.     }  
  12. }  

注:如果没有添加配置类,进入监控页面同样也会显示:Unable to connect to Command Metric Stream. 同上方proxyStreamAllowList: localhost 未添加设置显示页面一样 。

  1. 显示页面

  完成以上步骤,打开链接http://localhost:8081/ccti/im/bridge/hystrix 。显示以下页面,表示成功了。打开下 方页面后,还需上方输入框内输入以下路径 http://localhost:8081/ccti/im/bridge/actuator/hystrix.stream,点击Monitor Stream进入监控页面

  1. 监控页面

  • Actuator 健康检查
  1. 添加依赖

(前面仪表盘已添加这个依赖,有了无需再添加)

  1. <dependency>  
  2.    <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-actuator</artifactId>  
  4. </dependency>  
  1. 配置yml

#-----------------健康检查配置-----------------------

  1. management:  
  2.   endpoints:  
  3.     health:  
  4.       show-details: always  
  5.     web:  
  6.       exposure:  
  7.         include: health,info,env,loggers  

注:

health: 包含健康检查相关功能。

info: 包含信息展示功能。

env: 包含环境变量相关功能。

loggers: 包含日志记录相关功能

还可以根据需求配置其他信息。

  1. 访问路径

例如:127.0.0.1:8081/ccti/im/bridge/actuator/health

能访问的端点根据配置 include内容有关。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值