- hystrix熔断器的使用
- 添加依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
- </dependency>
- yml配置
- #设置Feign的配置
- feign:
- hystrix:
- # 开启Hystrix,否则@FeignClient中的fallbackFactory配置不起作用。
- enabled: true
- #-----------------Hystrix配置-----------------------
- hystrix:
- command:
- default:
- metrics:
- rollingStats:
- #设置滚动时间窗为5秒
- timeInMilliseconds: 5000
- execution:
- isolation:
- thread:
- # 设置命令执行的默认超时时间,单位毫秒
- timeoutInMilliseconds: 10000
- timeout:
- # 是否启用超时,如果不启用上面的值也不用配置。
- enabled: true
- circuitBreaker:
- # 是否启用断路器
- enabled: true
- # 单位时间内请求的总量需要达到阈值
- requestVolumeThreshold: 2
- # 错误率阈值,当错误率超过这个值,断路器打开
- errorThresholdPercentage: 50
- # 断路器打开后,多久后尝试恢复服务
- sleepWindowInMilliseconds: 10000
- # 开启Hystrix Dashboard
- dashboard:
- proxyStreamAllowList: localhost
- enabled: true
注:requestVolumeThreshold单位时间内请求的总量需要达到阈值,换句话说,假如某个窗口期内的请求总数都不到该配置值,那么断路器连发生的资格都没有。例如,如果值是20,那么如果在滚动窗口中只接收到19个请求(比如一个10秒的窗口),即便所有19个请求都失败了,熔断判断逻辑也不会被触发。测试时可以设置小一些,这样更容易被测出。
errorThresholdPercentage 该属性表示熔断触发条件,即触发熔断时错误百分比。一旦打到这个触发比例,断路器就进入“打开”状态,但前提是,需要整体的请求流量能够满足设置的容量。此配置项默认值是 50,即窗口时间内超过 50% 的请求失败后会打开熔断器将后续请求快速失败。
sleepWindowInMilliseconds可以理解为一个触发断路器的周期时间值,此配置项指定了熔断器打开后经过多长时间允许一次请求尝试执行,测试时可以设置大些,这样更容易被测出。
- 启动类添加注解
启动类添加@EnableHystrix 注解
- FallbackFactory降级处理类
- @FeignClient(name = "imGateWayClientFeign",
- url = "${im-gateway.url}",
- fallbackFactory = ImGateWayClientFallbackFactory.class)
- public interface ImGateWayClientFeign {
- @PostMapping("/handleEvent")
- CommonResult<Boolean> handleEvent(@Valid @RequestBody ImEventMessage imMessage);
- }
- @Slf4j
- @Component
- public class ImGateWayClientFallbackFactory implements FallbackFactory<ImGateWayClientFeign> {
- @Override
- public ImGateWayClientFeign create(Throwable throwable) {
- return new ImGateWayClientFeign() {
- @Override
- public CommonResult<Boolean> handleEvent(ImEventMessage imMessage) {
- log.error("handleEvent error imMessage:{}", JSON.toJSONString(imMessage));
- log.error(throwable.getMessage());
- return CommonResult.fail(ResultCode.COMMON_FAIL.getCode(), ResultCode.COMMON_FAIL.getMessage());
- }
- };
- }
- }
注:在配置上方信息后,如果没有添加@Component,会启动失败,异常消息主要如下:
- 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
- 客户端测试方法(抛出异常)
- @PostMapping("/handleEvent")
- public CommonResult<Boolean> handleEvent(@Valid @RequestBody ImEventMessage imMessage) {
- if(imMessage.getCid().equals("111")){
- throw new RuntimeException("测试异常");
- }
- }
- }
- Apifox测试
传参时cid传“111”,客户端会响应 “调用网关服务失败”。此时失败异常数+1。
如此重复3次调用(次数根据阈值设定来尝试),第四次修改成正确的cid,此时应响应“调用成功”,但仍然返回 “调用网关服务失败”。说明 触发了熔断,不再调用客户端,直接返回异常。 10秒后(根据设定恢复时间)再次请求,客户端响应“调用成功”
- Hystrix Dashboard仪表盘的使用
- 添加依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-actuator</artifactId>
- </dependency>
- yml配置
# 开启Hystrix Dashboard,在hystrix配置基础下可以增加如下配置。
- dashboard:
- proxyStreamAllowList: localhost
- enabled: true
注:proxyStreamAllowList: localhost如果不添加,监控页面也会显示:Unable to connect to Command Metric Stream.
访问本地服务会出现下发情况。控制台会出现异常,异常信息如下。
- 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.
- 启动类添加注解
启动类添加注解@EnableHystrixDashboard
- 添加配置类
- @Configuration
- public class HystrixServletDefinitions {
- @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;
- }
- }
注:如果没有添加配置类,进入监控页面同样也会显示:Unable to connect to Command Metric Stream. 同上方proxyStreamAllowList: localhost 未添加设置显示页面一样 。
- 显示页面
完成以上步骤,打开链接http://localhost:8081/ccti/im/bridge/hystrix 。显示以下页面,表示成功了。打开下 方页面后,还需上方输入框内输入以下路径 http://localhost:8081/ccti/im/bridge/actuator/hystrix.stream,点击Monitor Stream进入监控页面
- 监控页面
- Actuator 健康检查
- 添加依赖
(前面仪表盘已添加这个依赖,有了无需再添加)
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-actuator</artifactId>
- </dependency>
- 配置yml
#-----------------健康检查配置-----------------------
- management:
- endpoints:
- health:
- show-details: always
- web:
- exposure:
- include: health,info,env,loggers
注:
health: 包含健康检查相关功能。
info: 包含信息展示功能。
env: 包含环境变量相关功能。
loggers: 包含日志记录相关功能
还可以根据需求配置其他信息。
- 访问路径
例如:127.0.0.1:8081/ccti/im/bridge/actuator/health
能访问的端点根据配置 include内容有关。