SpringCloud Hystrix 实战

一、配置

1.引入jar包

单独使用hystrix ,不配合openFegin使用的话,单独使用hystrix,需要引入spring-cloud-starter-netflix-hystrix包。要使用的hystrix-dashboard 界面的话需要引入spring-boot-starter-actuator 包和spring-cloud-starter-netflix-hystrix-dashboard 包

  <!--不配合openfegin单独使用hystrix--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency><!-- pom必须引入actuator,所有需要被监控的服务都要引入actuator--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><!-- 引入 hystrix-dashboard--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency>

1.2 开启注解

要使用的 熔断讲解功能需要开启@EnableHystrix注解,要开启HystrixDashboard 监控功能
需要@EnableHystrixDashboard 注解

配置HystrixDashboard 监控访问的 stream的监控流serverlet
/hystrix.stream

@SpringBootApplication
//开启Hystrix熔断,或者使用@EnableCircuitBreaker
@EnableHystrix
//开启HystrixDashboard
@EnableHystrixDashboard
public class AmasterReportServerApplication {public static void main(String[] args) {SpringApplication.run(AmasterReportServerApplication.class, args);}}@Beanpublic ServletRegistrationBean getServlet() {HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");return registrationBean;}

由于springcloud的版本不同,有些版本在访问界面的时候不配置ServletRegistrationBean 会在打开hystrixdash的访问页面,输入监控的hystrix.stream地址,在进入hystrixdash的监控界面会,监控解密那上会显示 Unable to connect to Command Metric Stream。有些版本不需要配置ServletRegistrationBean

1.3 在调用方法上配置降级方法和熔断条件

@Slf4j
public class ReportServiceImpl {@Autowiredprivate RestTemplate restTemplate;@HystrixCommand( commandProperties = {@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10")},fallbackMethod = "ribbionAloneUseFallback")public List<String> ribbionAloneUse(String clientMark, String path) {String url  = String.format("http://%s%s",clientMark,path);ResponseEntity<List> entity = restTemplate.getForEntity(url, List.class);return  entity.getBody();}//ribbionAloneUse方法降级服务public List<String> ribbionAloneUseFallback(String clientMark,String path,Throwable e){log.error(e.getMessage(),e);String url  = String.format("http://%s%s",clientMark,path);return Arrays.asList("触发降级"+url) ;}
}

注意:在配置熔断方法的时候,目标方法的降级方法,入参和返回值类型要相同。要不然在调用ribbionAloneUse 的时候会报

hystrix回调方法报错:fallback method wasn‘t found

hystrix降级的fallback方法需要与原方法有相同的返回类型和参数列表,fallback方法可以在参数列表后加一个Throwable类型参数用于接收异常信息

1.4 配置文件,配置dashboard的访问代理允许许可

amaster-report-server的服务配置文件

spring:application:name: amaster-report-servercloud:load-balancer:
#            ribbon:
#                eager-load:
#                    enabled: true # 开启饥饿加载,这里为配合注册中心使用,因此关闭掉懒加载
#                    clients: # 指定饥饿加载的服务名称
#                        - amaster-work-server   # 用户服务
#                        - amaster-config-env # 仓库服务#开启重试机制,默认是关闭的retry:enabled: trueamaster-work-server:ribbon:#请求连接的超时时间ConnectTimeout: 250#请求处理的超时时间ReadTimeout: 1000#对所有操作请求都进行重试,默认false,只有GET请求会重试;这是防止POST等对数据有影响的请求在重试后因为接口未做幂等性导致数据异常,影响较大OkToRetryOnAllOperations: true#切换实例的重试次数MaxAutoRetriesNextServer: 2#对当前实例的重试次数MaxAutoRetries: 1# 服务的实例地址列表listOfServers: localhost:9005,localhost:9015#给某个微服务配置负载均衡规则NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
#配置运训访问的监控地址列表
hystrix:dashboard:# "127.0.0.1"proxy-stream-allow-list: "**"#hystrix:
#    dashboard:
#        # "127.0.0.1"
#        proxy-stream-allow-list: "localhost"# 暴漏监控信息
management:endpoints:web:exposure:include: hystrix.stream# 暴漏监控信息
#management:
#    endpoints:
#        web:
#            exposure:
#                include: "*"

如果不开启开启允许hystrixDashboard 的监控流代理地址,在通过监控首页输入监控服务地址hystrx.stream的访问监控地址的时候会报如下错

2024-04-27 00:00:29.767  WARN 15572 --- [nio-9007-exec-5] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.
2024-04-27 00:00:29.767  WARN 15572 --- [io-9007-exec-10] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.
2024-04-27 00:01:13.625  WARN 15572 --- [nio-9007-exec-8] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.
2024-04-27 00:01:13.625  WARN 15572 --- [nio-9007-exec-7] ashboardConfiguration$ProxyStreamServlet : Origin parameter: http://127.0.0.1:9007/amaster-report-server/actuator/hystrix is not in the allowed list of proxy host names.  If it should be allowed add it to hystrix.dashboard.proxyStreamAllowList.

1.5 测试

开启两个服务amaster-work-server 的两个服务
amaster-work-server 9015 和amaster-work-server 9005

在这里插入图片描述
在这里插入图片描述
amaster-report 服务未注册到中心,调用amaster-work-serve 的两个服务 通过ribbion的listOfServers 进行配置调用。可以看到两个服务被随机轮询调用;
当调用接口http://127.0.0.1:9007/amaster-report-server/env/get/report/ribbion/alone/use/v1 调用的时候会打印

2024-04-26 22:01:07.576  INFO 12804 --- [rtServiceImpl-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client: amaster-work-server instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=amaster-work-server,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2024-04-26 22:01:07.585  INFO 12804 --- [rtServiceImpl-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2024-04-26 22:01:07.613  INFO 12804 --- [rtServiceImpl-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client amaster-work-server initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=amaster-work-server,current list of Servers=[localhost:9005, localhost:9015],Load balancer stats=Zone stats: {unknown=[Zone:unknown;	Instance count:2;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:localhost:9015;	Zone:UNKNOWN;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
, [Server:localhost:9005;	Zone:UNKNOWN;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:com.netflix.loadbalancer.ConfigurationBasedServerList@36eda38c

在这里插入图片描述
如果其中一个方不正常在调用的时候,在轮询调用到不正常的服务的时候就走,快速失败的方法

在这里插入图片描述

}ServerList:com.netflix.loadbalancer.ConfigurationBasedServerList@5d209707
2024-04-26 23:33:32.223 ERROR 1076 --- [ HystrixTimer-5] c.z.b.a.r.service.ReportServiceImpl      : nullcom.netflix.hystrix.exception.HystrixTimeoutException: nullat com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1142) ~[hystrix-core-1.5.18.jar:1.5.18]at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.5.18.jar:1.5.18]at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.5.18.jar:1.5.18]at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.5.18.jar:1.5.18]at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1159) [hystrix-core-1.5.18.jar:1.5.18]at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:99) [hystrix-core-1.5.18.jar:1.5.18]at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_401]at java.util.concurrent.FutureTask.runAndReset$$$capture(FutureTask.java:308) [na:1.8.0_401]at java.util.concurrent.FutureTask.runAndReset(FutureTask.java) [na:1.8.0_401]at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_401]at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [na:1.8.0_401]at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_401]at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_401]at java.lang.Thread.run(Thread.java:750) [na:1.8.0_401]

二 控制台 dashboard的访问

http://127.0.0.1:9007/amaster-report-server/actuator/hystrix.stream

在这里插入图片描述

访问成功后界面显示如下
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/652389.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

交互式探索微生物群落与生态功能的关系

微生物群落在生态系统中发挥则重要功能&#xff0c;我们在对微生物群落进行分析时&#xff0c;会将不同分类水平&#xff08;从门到属&#xff09;的微生物类群的相对丰度与测定的某一生态功能进行相关性分析。但由于微生物类群数较多&#xff0c;又有不同的分类水平&#xff0…

机械臂过程

rosdep install --from-paths src --ignore-src --rosdistro melodic0、安装机械手臂 官方教程&#xff1a; 前人教程&#xff1a;UR5机械臂仿真实例 rosdep update 出错&#xff0c;使用小鱼的大佬的 一键配置 wget http://fishros.com/install -O fishros && . fish…

【链表】Leetcode 合并k个升序链表

题目讲解 23. 合并 K 个升序链表 算法讲解 首先将所有链表的当前首节点找出来&#xff0c;判断当前的结点哪一个最小&#xff0c;链接到结果链表的后面&#xff0c;但是怎么寻找当前的最小结点&#xff1a;就需要使用优先级队列&#xff0c;我们建立一个小堆&#xff0c;然后…

池化整合多元数据库,zData X 一体机助力证券公司IT基础架构革新

引言 近期&#xff0c;云和恩墨 zData X 多元数据库一体机&#xff08;以下简称 zData X&#xff09;在某证券公司的OA、短信和CRM业务系统中成功上线&#xff0c;标志着其IT基础架构完成从集中式存储向池化高性能分布式存储的转变。zData X 成功整合了该证券公司使用的达梦、O…

AcrelEMS-MH民航机场智慧能源管平台解决方案【可靠供电/降低能耗/高效运维】

民航机场行业背景 自2012年以来&#xff0c;我国民航运输规模出现了显著增长&#xff0c;旅客运输量&#xff1a;从2012年的3.19亿人次上升至2019年的6.6亿人次&#xff08;注&#xff1a;为剔除疫情影响&#xff0c;此处采取疫情前2019年的数据&#xff0c;下同&#xff09;&…

设计不外流,保护创意的同时锁住图纸安全!

在设计行业中&#xff0c;图纸和创意文稿的安全至关重要&#xff0c;因为它们体现了企业的创新能力和核心竞争力。华企盾DSC数据防泄密系统提供了一系列功能&#xff0c;可以有效地保护这些珍贵的设计和文档不被外泄。以下是如何利用华企盾DSC系统保障设计图纸安全的关键措施&a…

局部多项式近似与 AMPM 算法

kappa3; %已在您的代码中定义% 定义窗口大小 windowSize (2*kappa1);% 初始化梯度估计值 [rows, cols] size(wrappedPhase); phi_y zeros(rows, cols); phi_x zeros(rows, cols);% 遍历每个窗口 for m 1kappa:rows-kappafor n 1kappa:cols-kappa% 提取局部窗口Z_mn wrap…

51-46 MCDiff,可控视频合成的运动条件扩散模型

23年4月&#xff0c;加州大学、Nvidia、Meta和Google联合发布了MCDiff模型。这是继DragNUWA之后&#xff0c;咱们介绍的第二篇Motion-guiding类视频生成模型。 Abstract 扩散模型的最新进展极大地提高了合成内容的质量和多样性。为了利用扩散模型的表达能力&#xff0c;研究人…

边OTG边充电芯片LDR6500

随着科技的飞速发展&#xff0c;智能移动设备已成为我们生活中不可或缺的一部分。而在这些设备的连接与数据传输中&#xff0c;Type-C接口以其高效、便捷的特性逐渐占据了主导地位。OTG&#xff08;On-The-Go&#xff09;技术则进一步扩展了Type-C接口的功能&#xff0c;使得设…

LT9611UXC双端口 MIPI DSI/CSI 转 HDMI2.0,带音频

1. 说明 LT9611UXC 是一款高性能 MIPI DSI/CSI 至 HDMI2.0 转换器。MIPI DSI/CSI 输入具有可配置的单端口或双端口&#xff0c;具有 1 个高速时钟通道和 1~4 个高速数据通道&#xff0c;工作速率最高为 2Gbps/通道&#xff0c;可支持高达 16Gbps 的总带宽。 LT9611UXC 支持突发…

网络靶场实战-物联网安全Unicorn框架初探

背景 Unicorn 是一款基于 QEMU 的快速 CPU 模拟器框架&#xff0c;可以模拟多种体系结构的指令集&#xff0c;包括 ARM、MIPS、PowerPC、SPARC 和 x86 等。Unicorn使我们可以更好地关注 CPU 操作, 忽略机器设备的差异。它能够在虚拟内存中加载和运行二进制代码&#xff0c;并提…

JAVA:maven-->>检查 所有依赖 与 环境 兼容

内容 为了确保你项目中的所有依赖都彼此兼容&#xff0c;并与你的环境相适应&#xff0c;你可以利用 Maven 的依赖管理功能。Maven 有助于解决、升级&#xff0c;并对齐所有库的版本&#xff0c;以避免任何不一致或冲突。以下是检查兼容性的步骤&#xff1a; ### 检查兼容性的…