SpringCloud Hystrix熔断器如何使用

免费教程   2024年05月10日 3:20  

本文小编为大家详细介绍“SpringCloudHystrix熔断器如何使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringCloudHystrix熔断器如何使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

(hi si ju ke si)概述

Hystix 是 Netflix 开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败(雪崩)。

雪崩:一个服务失败,导致整条链路的服务都失败的情形。

Hystix 主要功能

隔离

降级

熔断

限流

隔离

线程池隔离

信号量隔离

Hystrix 降级

Hystix 降级:当服务发生异常或调用超时,返回默认数据

Hystrix降级-服务提供方

在服务提供方,引入 hystrix 依赖

定义降级方法

使用 @HystrixCommand 注解配置降级方法

在启动类上开启Hystrix功能:@EnableCircuitBreaker

初始化程序和Fiegn程序一致

需要修改的程序

packagecom.itheima.provider;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;importorg.springframework.cloud.netflix.eureka.EnableEurekaClient;/***启动类*/@EnableEurekaClient//该注解在新版本中可以省略@SpringBootApplication@EnableCircuitBreaker///开启Hystrix功能publicclassProviderApp{publicstaticvoidmain(String[]args){SpringApplication.run(ProviderApp.class,args);}}

测试的程序

packagecom.itheima.provider.controller;importcom.itheima.provider.domain.Goods;importcom.itheima.provider.service.GoodsService;importcom.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;importcom.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.Date;/***GoodsController服务提供方*/@RestController@RequestMapping("/goods")publicclassGoodsController{@AutowiredprivateGoodsServicegoodsService;@Value("${server.port}")privateintport;/***降级:*1出现异常*2调用服务超时*默认1s超时**@HystrixCommand(fallbackMethod="findOne_fallback")*fallbackMethod指定降级后的名称*@paramid*@return*/@GetMapping("/findOne/{id}")@HystrixCommand(fallbackMethod="findOne_fallback",commandProperties={//设置Hystrix的超时时间默认1s@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")})///指定降级后的方法publicGoodsfindOne(@PathVariable("id")intid){///1造个异常//inti=3/0;try{Thread.sleep(2000);//sleepinterrupted}catch(InterruptedExceptione){e.printStackTrace();}Goodsgoods=goodsService.findOne(id);goods.setTitle(goods.getTitle()+":"+port);//将端口号,设置到了商品上returngoods;}/***定义降级放啊*1方法的返回值需要和原方法一样*2方法参数需要和原方法一样*/publicGoodsfindOne_fallback(intid){Goodsgoods=newGoods();goods.setTitle("降级了~~~");returngoods;}}

指定坐标

<!--hystrix--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>Hystrix降级-服务消费方

feign 组件已经集成了 hystrix 组件。

定义feign 调用接口实现类,复写方法,即降级方法

在 @FeignClient 注解中使用 fallback 属性设置降级处理类。

配置开启 feign.hystrix.enabled = true

provider与Fiegin一致

application.yml修改

server: port: 9000

eureka: instance: hostname: localhost # 主机名 client: service-url: defaultZone: http://localhost:8761/eurekaspring: application: name: hystrix-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径#开启feign对hystrix支持feign: hystrix: enabled: true

ConsumerApp修改

packagecom.itheima.consumer;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.client.discovery.EnableDiscoveryClient;importorg.springframework.cloud.netflix.eureka.EnableEurekaClient;importorg.springframework.cloud.openfeign.EnableFeignClients;@EnableDiscoveryClient//激活DiscoveryClient@EnableEurekaClient@SpringBootApplication@EnableFeignClients//开启Feign的功能publicclassConsumerApp{publicstaticvoidmain(String[]args){SpringApplication.run(ConsumerApp.class,args);}}

修改GoodsFeignClient方法

packagecom.itheima.consumer.feign;importcom.itheima.consumer.domain.Goods;importorg.springframework.cloud.openfeign.FeignClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;@FeignClient(value="HYSTRIX-PROVIDER",fallback=GoodsFeignClientFallback.class)publicinterfaceGoodsFeignClient{@GetMapping("/goods/findOne/{id}")publicGoodsfindGoodsById(@PathVariable("id")intid);}

复写方法

packagecom.itheima.consumer.feign;importcom.itheima.consumer.domain.Goods;importorg.springframework.stereotype.Component;/***Fegin客户端降级处理类*1定义类实现Feign客户端接口*2使用@Component注解将该类的Bean加入SpringIOC容器*/@ComponentpublicclassGoodsFeignClientFallbackimplementsGoodsFeignClient{@OverridepublicGoodsfindGoodsById(intid){Goodsgoods=newGoods();goods.setTitle("又被降级了~~");returngoods;}}Hystrix 熔断

Hystrix 熔断机制,用于监控微服务调用情况,当失败的情况达到预定的阈值(5秒失败20次),会打开断路器,拒绝所有请求,直到服务恢复正常为止。

circuitBreaker.sleepWindowInMilliseconds:监控时间

circuitBreaker.requestVolumeThreshold:失败次数

circuitBreaker.errorThresholdPercentage:失败率

//设置Hystrix的超时时间默认1s@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000"),//监控的时间默认5000ms@HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="1000"),//失败次数,默认20次@HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="2"),//失败率百分之50@HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="100")Hystrix 熔断监控

Hystrix 提供了 Hystrix-dashboard 功能,用于实时监控微服务运行状态。

但是Hystrix-dashboard只能监控一个微服务。

Netflix 还提供了 Turbine ,进行聚合监控。

Turbine聚合监控搭建监控模块

1. 创建监控模块

创建hystrix-monitor模块,使用Turbine聚合监控多个Hystrix dashboard功能,

2. 引入Turbine聚合监控起步依赖

<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>hystrix-parent</artifactId><groupId>com.itheima</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>hystrix-monitor</artifactId><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><!--单独熔断监控--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency><!--聚合熔断监控--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-turbine</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

3. 修改application.yml

spring: application.name: hystrix-monitorserver: port: 8769turbine: combine-host-port: true # 配置需要监控的服务名称列表 app-config: hystrix-provider,hystrix-consumer cluster-name-expression: "'default'" aggregator: cluster-config: default #instanceUrlSuffix: /actuator/hystrix.streameureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/

4. 创建启动类

@SpringBootApplication@EnableEurekaClient@EnableTurbine//开启Turbine很聚合监控功能@EnableHystrixDashboard//开启Hystrix仪表盘监控功能publicclassHystrixMonitorApp{publicstaticvoidmain(String[]args){SpringApplication.run(HystrixMonitorApp.class,args);}}修改被监控模块

需要分别修改 hystrix-provider 和 hystrix-consumer 模块:

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</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency>

2、配置Bean

此处为了方便,将其配置在启动类中。

@BeanpublicServletRegistrationBeangetServlet(){HystrixMetricsStreamServletstreamServlet=newHystrixMetricsStreamServlet();ServletRegistrationBeanregistrationBean=newServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/actuator/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");returnregistrationBean;}

3、启动类上添加注解@EnableHystrixDashboard

@EnableDiscoveryClient@EnableEurekaClient@SpringBootApplication@EnableFeignClients@EnableHystrixDashboard//开启Hystrix仪表盘监控功能publicclassConsumerApp{publicstaticvoidmain(String[]args){SpringApplication.run(ConsumerApp.class,args);}@BeanpublicServletRegistrationBeangetServlet(){HystrixMetricsStreamServletstreamServlet=newHystrixMetricsStreamServlet();ServletRegistrationBeanregistrationBean=newServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/actuator/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");returnregistrationBean;}}启动测试

1、启动服务:

eureka-server

hystrix-provider

hystrix-consumer

hystrix-monitor

2、访问:

在浏览器访问http://localhost:8769/hystrix/ 进入Hystrix Dashboard界面

界面中输入监控的Url地址 http://localhost:8769/turbine.stream,监控时间间隔2000毫秒和title,如下图

实心圆:它有颜色和大小之分,分别代表实例的监控程度和流量大小。如上图所示,它的健康度从绿色、黄色、橙色、红色递减。通过该实心圆的展示,我们就可以在大量的实例中快速的发现故障实例和高压力实例。

曲线:用来记录 2 分钟内流量的相对变化,我们可以通过它来观察到流量的上升和下降趋势。

读到这里,这篇“SpringCloudHystrix熔断器如何使用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。

域名注册
购买VPS主机

您或许对下面这些文章有兴趣:                    本月吐槽辛苦排行榜

看贴要回贴有N种理由!看帖不回贴的后果你懂得的!


评论内容 (*必填):
(Ctrl + Enter提交)   

部落快速搜索栏

各类专题梳理

网站导航栏

X
返回顶部