国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

詳解Spring Cloud Hystrix斷路器實現容錯和降級

2024-07-14 08:40:37
字體:
來源:轉載
供稿:網友

簡介

Spring cloud提供了Hystrix容錯庫用以在服務不可用時,對配置了斷路器的方法實行降級策略,臨時調用備用方法。這篇文章將創建一個產品微服務,注冊到eureka服務注冊中心,然后我們使用web客戶端訪問/products API來獲取產品列表,當產品服務故障時,則調用本地備用方法,以降級但正常提供服務。

基礎環境

  1. JDK 1.8
  2. Maven 3.3.9
  3. IntelliJ 2018.1

Git:項目源碼

添加產品服務

在intelliJ中創建一個新的maven項目,使用如下配置

  1. groupId: cn.zxuqian
  2. artifactId: productService

然后在pom.xml中添加如下代碼:

<?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">  <modelVersion>4.0.0</modelVersion>  <groupId>cn.zxuqian</groupId>  <artifactId>productService</artifactId>  <version>1.0-SNAPSHOT</version>  <parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>2.0.1.RELEASE</version>    <relativePath/>  </parent>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <java.version>1.8</java.version>  </properties>  <dependencies>    <dependency>      <groupId>org.springframework.cloud</groupId>      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>    </dependency>    <dependency>      <groupId>org.springframework.cloud</groupId>      <artifactId>spring-cloud-starter-config</artifactId>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-test</artifactId>      <scope>test</scope>    </dependency>  </dependencies>  <dependencyManagement>    <dependencies>      <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-dependencies</artifactId>        <version>Finchley.M9</version>        <type>pom</type>        <scope>import</scope>      </dependency>    </dependencies>  </dependencyManagement>  <build>    <plugins>      <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-maven-plugin</artifactId>      </plugin>    </plugins>  </build>  <repositories>    <repository>      <id>spring-milestones</id>      <name>Spring Milestones</name>      <url>https://repo.spring.io/libs-milestone</url>      <snapshots>        <enabled>false</enabled>      </snapshots>    </repository>  </repositories></project>

我們繼續使用了spring-cloud-starter-netflix-eureka-client以使產品服務自動注冊到eureka服務中。然后還使用了spring-cloud-starter-config讀取配置服務中心的配置文件。這個項目只是一個簡單的spring web項目。

在src/main/resources下創建bootstrap.yml文件,添加如下內容:

spring: application:  name: product-service cloud:  config:   uri: http://localhost:8888

在配置中心的git倉庫中創建product-service.yml文件 添加如下配置并提交:

server: port: 8081

此配置指定了產品服務的端口為8081。接著創建Application類,添加如下代碼:

package cn.zxuqian;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@EnableDiscoveryClient@SpringBootApplicationpublic class Application {  public static void main(String[] args) {    SpringApplication.run(Application.class, args);  }}

@EnableDiscoveryClient注解將指示spring cloud自動把本服務注冊到eureka。最后創建cn.zxuqian.controllers.ProductController控制器,提供/products API,返回示例數據:

package cn.zxuqian.controllers;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ProductController {  @RequestMapping("/products")  public String productList() {    return "外套,夾克,毛衣,T恤";  }}

配置Web客戶端

打開我們之前創建的web項目,在pom.xml中新添Hystrix依賴:

<dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>

然后更新Application類的代碼:

package cn.zxuqian;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.client.RestTemplateBuilder;import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.context.annotation.Bean;import org.springframework.web.client.RestTemplate;@EnableCircuitBreaker@EnableDiscoveryClient@SpringBootApplicationpublic class Application {  public static void main(String[] args) {    SpringApplication.run(Application.class, args);  }  @Bean  public RestTemplate rest(RestTemplateBuilder builder) {    return builder.build();  }}

這里使用@EnableCircuitBreaker來開啟斷路器功能,然后還添加了一個rest方法并使用@Bean注解。這部分屬于Spring依賴注入功能,使用@Bean標記的方法將告訴如何初始化此類對象,比如本例中就是使用RestTemplateBuilder來創建一個RestTemplate的對象,這個稍后在使用斷路器的service中用到。

創建cn.zxuqian.service.ProductService類,并添加如下代碼:

package cn.zxuqian.services;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.ServiceInstance;import org.springframework.cloud.client.discovery.DiscoveryClient;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;import java.util.List;@Servicepublic class ProductService {  private final RestTemplate restTemplate;  @Autowired  private DiscoveryClient discoveryClient;  public ProductService(RestTemplate restTemplate) {    this.restTemplate = restTemplate;  }  @HystrixCommand(fallbackMethod = "backupProductList")  public String productList() {    List<ServiceInstance> instances = this.discoveryClient.getInstances("product-service");    if(instances != null && instances.size() > 0) {      return this.restTemplate.getForObject(instances.get(0).getUri() + "/products", String.class);    }    return "";  }  public String backupProductList() {    return "夾克,毛衣";  }}

之所以要創建一個Service類,是因為Hystrix只能在標記為@Service或@Component的類中使用,這樣才能夠正常使用Spring Context所提供的API。這個以后深入Spring時再作說明。

使用@HystrixCommand注解后,Hystrix將監控被注解的方法即productList(底層使用proxy包裝此方法以此實現監控),一旦此方法的錯誤累積到一定門檻的時候,就會啟動斷路器,后續所有調用productList方法的請求都會失敗,而會臨時調用fallbackMethod指定的方法backupProductList(),然后當服務恢復正常時,斷路器就會關閉。

我們還在此類中用了DiscoveryClient用以尋找產品服務的uri地址,使用產品服務的spring.application.name配置項的值,即product-service作為serviceID傳給discoveryClient.getInstances()方法,然后會返回一個list,因為目前我們只有一個產品服務啟動著,所以只需要取第一個實例的uri地址即可。

然后我們使用RestTemplate來訪問產品服務的api,注意這里使用了Spring的構造方法注入,即之前我們用@Bean注解的方法會被用來初始化restTemplate變量,不需我們手動初始化。RestTemplate類提供了getForObject()方法來訪問其它Rest API并把結果包裝成對象的形式,第一個參數是要訪問的api的uri地址,第二參數為獲取的結果的類型,這里我們返回的是String,所以傳給他String.class。

backupProductList()方法返回了降級后的產品列表信息。

最后創建一個控制器cn.zxuqian.controllers.ProductController并添加如下代碼:

package cn.zxuqian.controllers;import cn.zxuqian.services.ProductService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ProductController {  @Autowired  private ProductService productService;  @RequestMapping("/products")  public String productList() {    return productService.productList();  }}

 這里使用ProductService為/products路徑提供數據。

測試

首先,我們使用spring-boot:run插件啟動配置中心服務,config-server,然后啟動eureka-server,再啟動product-service,最后啟動web客戶端,稍等片刻待eureka服務注冊成功之后訪問http://localhost:8080/products,正常的情況下會得到外套,夾克,毛衣,T恤結果,然后我們關閉product-service,之后再訪問同樣的路徑,會得到降級后的結果:夾克,毛衣

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁国市| 长海县| 高尔夫| 微博| 商洛市| 霍城县| 张家港市| 嵊泗县| 阿尔山市| 桂林市| 华容县| 泸水县| 金堂县| 三台县| 崇信县| 湟源县| 巴彦淖尔市| 广安市| 南城县| 石家庄市| 桃园县| 屏山县| 长岛县| 弥勒县| 新昌县| 萝北县| 新野县| 彭阳县| 遂昌县| 张家界市| 宜兰市| 曲周县| 集贤县| 鄂温| 宁南县| 德兴市| 华容县| 柯坪县| 家居| 海兴县| 丹东市|