Spring cloud提供了Hystrix容錯庫用以在服務不可用時,對配置了斷路器的方法實行降級策略,臨時調用備用方法。這篇文章將建立一個產品微服務,註冊到eureka服務註冊中心,而後咱們使用web客戶端訪問/products
API來獲取產品列表,當產品服務故障時,則調用本地備用方法,以降級但正常提供服務。php
Gitee碼雲java
在intelliJ中建立一個新的maven項目,使用以下配置git
而後在pom.xml中添加以下代碼:web
<?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項目。spring
在src/main/resources
下建立bootstrap.yml
文件,添加以下內容:apache
spring:
application:
name: product-service
cloud:
config:
uri: http://localhost:8888
複製代碼
在配置中心的git倉庫中建立product-service.yml
文件 添加以下配置並提交:bootstrap
server:
port: 8081
複製代碼
此配置指定了產品服務的端口爲8081。接着建立Application
類,添加以下代碼:api
package cn.zxuqian;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
複製代碼
@EnableDiscoveryClient
註解將指示spring cloud自動把本服務註冊到eureka。最後建立cn.zxuqian.controllers.ProductController
控制器,提供/products
API,返回示例數據:app
package cn.zxuqian.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
@RequestMapping("/products")
public String productList() {
return "外套,夾克,毛衣,T恤";
}
}
複製代碼
打開咱們以前建立的web
項目,在pom.xml
中新添Hystrix
依賴:maven
<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
@SpringBootApplication
public 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;
@Service
public 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;
@RestController
public 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,以後再訪問一樣的路徑,會獲得降級後的結果:夾克,毛衣
歡迎訪問個人博客zxuqian.cn/spring-clou…