您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“SpringCloud Hystrix熔斷器如何使用”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“SpringCloud Hystrix熔斷器如何使用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
Hystix 是 Netflix 開源的一個延遲和容錯庫,用于隔離訪問遠(yuǎn)程服務(wù)、第三方庫,防止出現(xiàn)級聯(lián)失?。ㄑ┍溃?。
雪崩:一個服務(wù)失敗,導(dǎo)致整條鏈路的服務(wù)都失敗的情形。
隔離
降級
熔斷
限流
線程池隔離
信號量隔離
Hystix 降級:當(dāng)服務(wù)發(fā)生異?;蛘{(diào)用超時,返回默認(rèn)數(shù)據(jù)
在服務(wù)提供方,引入 hystrix 依賴
定義降級方法
使用 @HystrixCommand 注解配置降級方法
在啟動類上開啟Hystrix功能:@EnableCircuitBreaker
需要修改的程序
package com.itheima.provider; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * 啟動類 */ @EnableEurekaClient //該注解 在新版本中可以省略 @SpringBootApplication @EnableCircuitBreaker ///開啟Hystrix功能 public class ProviderApp { public static void main(String[] args) { SpringApplication.run(ProviderApp.class,args); } }
測試的程序
package com.itheima.provider.controller; import com.itheima.provider.domain.Goods; import com.itheima.provider.service.GoodsService; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; /** * Goods Controller 服務(wù)提供方 */ @RestController @RequestMapping("/goods") public class GoodsController { @Autowired private GoodsService goodsService; @Value("${server.port}") private int port; /** * 降級: * 1 出現(xiàn)異常 * 2 調(diào)用服務(wù)超時 * 默認(rèn)1s超時 * *@HystrixCommand(fallbackMethod = "findOne_fallback") * fallbackMethod 指定降級后的名稱 * @param id * @return */ @GetMapping("/findOne/{id}") @HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = { //設(shè)置Hystrix的超時時間 默認(rèn)1s @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000") })///指定降級后的方法 public Goods findOne(@PathVariable("id") int id) { ///1 造個異常 //int i =3/0; try { Thread.sleep(2000);//sleep interrupted } catch (InterruptedException e) { e.printStackTrace(); } Goods goods = goodsService.findOne(id); goods.setTitle(goods.getTitle() + ":" + port);//將端口號,設(shè)置到了 商品標(biāo)題上 return goods; } /** * 定義降級放啊 * 1 方法的返回值需要和原方法一樣 * 2 方法參數(shù)需要和原方法一樣 */ public Goods findOne_fallback(int id) { Goods goods = new Goods(); goods.setTitle("降級了~~~"); return goods; } }
指定坐標(biāo)
<!--hystrix--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
feign 組件已經(jīng)集成了 hystrix 組件。
定義feign 調(diào)用接口實(shí)現(xiàn)類,復(fù)寫方法,即降級方法
在 @FeignClient 注解中使用 fallback 屬性設(shè)置降級處理類。
配置開啟 feign.hystrix.enabled = true
application.yml修改
server:
port: 9000eureka:
instance:
hostname: localhost # 主機(jī)名
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: hystrix-consumer # 設(shè)置當(dāng)前應(yīng)用的名稱。將來會在eureka中Application顯示。將來需要使用該名稱來獲取路徑
#開啟feign對hystrix支持
feign:
hystrix:
enabled: true
ConsumerApp修改
package com.itheima.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; @EnableDiscoveryClient // 激活DiscoveryClient @EnableEurekaClient @SpringBootApplication @EnableFeignClients //開啟Feign的功能 public class ConsumerApp { public static void main(String[] args) { SpringApplication.run(ConsumerApp.class,args); } }
修改GoodsFeignClient方法
package com.itheima.consumer.feign; import com.itheima.consumer.domain.Goods; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient(value = "HYSTRIX-PROVIDER",fallback = GoodsFeignClientFallback.class) public interface GoodsFeignClient { @GetMapping("/goods/findOne/{id}") public Goods findGoodsById(@PathVariable("id") int id); }
復(fù)寫方法
package com.itheima.consumer.feign; import com.itheima.consumer.domain.Goods; import org.springframework.stereotype.Component; /** * Fegin 客戶端降級處理類 * 1 定義類 實(shí)現(xiàn)Feign 客戶端接口 * 2 使用@Component注解將該類的Bean加入SpringIOC容器 */ @Component public class GoodsFeignClientFallback implements GoodsFeignClient{ @Override public Goods findGoodsById(int id) { Goods goods = new Goods(); goods.setTitle("又被降級了~~"); return goods; } }
Hystrix 熔斷機(jī)制,用于監(jiān)控微服務(wù)調(diào)用情況,當(dāng)失敗的情況達(dá)到預(yù)定的閾值(5秒失敗20次),會打開斷路器,拒絕所有請求,直到服務(wù)恢復(fù)正常為止。
circuitBreaker.sleepWindowInMilliseconds:監(jiān)控時間
circuitBreaker.requestVolumeThreshold:失敗次數(shù)
circuitBreaker.errorThresholdPercentage:失敗率
//設(shè)置Hystrix的超時時間 默認(rèn)1s @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"), //監(jiān)控的時間 默認(rèn)5000ms @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "1000"), //失敗次數(shù),默認(rèn)20次 @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "2"), //失敗率 百分之50 @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "100")
Hystrix 提供了 Hystrix-dashboard 功能,用于實(shí)時監(jiān)控微服務(wù)運(yùn)行狀態(tài)。
但是Hystrix-dashboard只能監(jiān)控一個微服務(wù)。
Netflix 還提供了 Turbine ,進(jìn)行聚合監(jiān)控。
1. 創(chuàng)建監(jiān)控模塊
創(chuàng)建hystrix-monitor模塊,使用Turbine聚合監(jiān)控多個Hystrix dashboard功能,
2. 引入Turbine聚合監(jiān)控起步依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="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.0 http://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> <!--單獨(dú)熔斷監(jiān)控--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId> </dependency> <!--聚合熔斷監(jiān)控--> <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-monitor
server:
port: 8769
turbine:
combine-host-port: true
# 配置需要監(jiān)控的服務(wù)名稱列表
app-config: hystrix-provider,hystrix-consumer
cluster-name-expression: "'default'"
aggregator:
cluster-config: default
#instanceUrlSuffix: /actuator/hystrix.stream
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
4. 創(chuàng)建啟動類
@SpringBootApplication @EnableEurekaClient @EnableTurbine //開啟Turbine 很聚合監(jiān)控功能 @EnableHystrixDashboard //開啟Hystrix儀表盤監(jiān)控功能 public class HystrixMonitorApp { public static void main(String[] args) { SpringApplication.run(HystrixMonitorApp.class, args); } }
需要分別修改 hystrix-provider 和 hystrix-consumer 模塊:
1、導(dǎo)入依賴:
<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
此處為了方便,將其配置在啟動類中。
@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; }
3、啟動類上添加注解@EnableHystrixDashboard
@EnableDiscoveryClient @EnableEurekaClient @SpringBootApplication @EnableFeignClients @EnableHystrixDashboard // 開啟Hystrix儀表盤監(jiān)控功能 public class ConsumerApp { public static void main(String[] args) { SpringApplication.run(ConsumerApp.class,args); } @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; } }
1、啟動服務(wù):
eureka-server
hystrix-provider
hystrix-consumer
hystrix-monitor
2、訪問:
在瀏覽器訪問http://localhost:8769/hystrix/ 進(jìn)入Hystrix Dashboard界面
界面中輸入監(jiān)控的Url地址 http://localhost:8769/turbine.stream,監(jiān)控時間間隔2000毫秒和title,如下圖
實(shí)心圓:它有顏色和大小之分,分別代表實(shí)例的監(jiān)控程度和流量大小。如上圖所示,它的健康度從綠色、黃色、橙色、紅色遞減。通過該實(shí)心圓的展示,我們就可以在大量的實(shí)例中快速的發(fā)現(xiàn)故障實(shí)例和高壓力實(shí)例。
曲線:用來記錄 2 分鐘內(nèi)流量的相對變化,我們可以通過它來觀察到流量的上升和下降趨勢。
讀到這里,這篇“SpringCloud Hystrix熔斷器如何使用”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。