溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Cloud入門教程-Hystrix斷路器實(shí)現(xiàn)容錯(cuò)和降級(jí)

發(fā)布時(shí)間:2020-07-06 18:38:19 來源:網(wǎng)絡(luò) 閱讀:5951 作者:zxuqian 欄目:建站服務(wù)器

簡介

Spring cloud提供了Hystrix容錯(cuò)庫用以在服務(wù)不可用時(shí),對(duì)配置了斷路器的方法實(shí)行降級(jí)策略,臨時(shí)調(diào)用備用方法。這篇文章將創(chuàng)建一個(gè)產(chǎn)品微服務(wù),注冊(cè)到eureka服務(wù)注冊(cè)中心,然后我們使用web客戶端訪問/products API來獲取產(chǎn)品列表,當(dāng)產(chǎn)品服務(wù)故障時(shí),則調(diào)用本地備用方法,以降級(jí)但正常提供服務(wù)。

基礎(chǔ)環(huán)境

  • JDK 1.8
  • Maven 3.3.9
  • IntelliJ 2018.1
  • Git

項(xiàng)目源碼

Gitee碼云

添加產(chǎn)品服務(wù)

在intelliJ中創(chuàng)建一個(gè)新的maven項(xiàng)目,使用如下配置

  • groupId: cn.zxuqian
  • 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>

我們繼續(xù)使用了spring-cloud-starter-netflix-eureka-client以使產(chǎn)品服務(wù)自動(dòng)注冊(cè)到eureka服務(wù)中。然后還使用了spring-cloud-starter-config讀取配置服務(wù)中心的配置文件。這個(gè)項(xiàng)目只是一個(gè)簡單的spring web項(xiàng)目。

在src/main/resources下創(chuàng)建bootstrap.yml文件,添加如下內(nèi)容:

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

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

server:
  port: 8081

此配置指定了產(chǎn)品服務(wù)的端口為8081。接著創(chuàng)建Application類,添加如下代碼:

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自動(dòng)把本服務(wù)注冊(cè)到eureka。最后創(chuàng)建cn.zxuqian.controllers.ProductController控制器,提供/products API,返回示例數(shù)據(jù):

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客戶端

打開我們之前創(chuàng)建的web項(xiàng)目,在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
@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來開啟斷路器功能,然后還添加了一個(gè)rest方法并使用@Bean注解。這部分屬于Spring依賴注入功能,使用@Bean標(biāo)記的方法將告訴如何初始化此類對(duì)象,比如本例中就是使用RestTemplateBuilder來創(chuàng)建一個(gè)RestTemplate的對(duì)象,這個(gè)稍后在使用斷路器的service中用到。

創(chuàng)建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 "夾克,毛衣";
    }
}

之所以要?jiǎng)?chuàng)建一個(gè)Service類,是因?yàn)镠ystrix只能在標(biāo)記為@Service@Component的類中使用,這樣才能夠正常使用Spring Context所提供的API。這個(gè)以后深入Spring時(shí)再作說明。使用`@HystrixCommand`注解后,Hystrix將監(jiān)控被注解的方法即`productList`(底層使用proxy包裝此方法以此實(shí)現(xiàn)監(jiān)控),一旦此方法的錯(cuò)誤累積到一定門檻的時(shí)候,就會(huì)啟動(dòng)斷路器,后續(xù)所有調(diào)用`productList`方法的請(qǐng)求都會(huì)失敗,而會(huì)臨時(shí)調(diào)用`fallbackMethod`指定的方法`backupProductList()`,然后當(dāng)服務(wù)恢復(fù)正常時(shí),斷路器就會(huì)關(guān)閉。
br/>使用`@HystrixCommand`注解后,Hystrix將監(jiān)控被注解的方法即`productList`(底層使用proxy包裝此方法以此實(shí)現(xiàn)監(jiān)控),一旦此方法的錯(cuò)誤累積到一定門檻的時(shí)候,就會(huì)啟動(dòng)斷路器,后續(xù)所有調(diào)用`productList`方法的請(qǐng)求都會(huì)失敗,而會(huì)臨時(shí)調(diào)用`fallbackMethod`指定的方法`backupProductList()`,然后當(dāng)服務(wù)恢復(fù)正常時(shí),斷路器就會(huì)關(guān)閉。
DiscoveryClient用以尋找產(chǎn)品服務(wù)的uri地址,使用產(chǎn)品服務(wù)的spring.application.name配置項(xiàng)的值,即product-service作為serviceID傳給discoveryClient.getInstances()方法,然后會(huì)返回一個(gè)list,因?yàn)槟壳拔覀冎挥幸粋€(gè)產(chǎn)品服務(wù)啟動(dòng)著,所以只需要取第一個(gè)實(shí)例的uri地址即可。
然后我們使用RestTemplate來訪問產(chǎn)品服務(wù)的api,注意這里使用了Spring的構(gòu)造方法注入,即之前我們用@Bean注解的方法會(huì)被用來初始化restTemplate變量,不需我們手動(dòng)初始化。RestTemplate類提供了getForObject()方法來訪問其它Rest API并把結(jié)果包裝成對(duì)象的形式,第一個(gè)參數(shù)是要訪問的api的uri地址,第二參數(shù)為獲取的結(jié)果的類型,這里我們返回的是String,所以傳給他String.class。
backupProductList()方法返回了降級(jí)后的產(chǎn)品列表信息。

最后創(chuàng)建一個(gè)控制器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路徑提供數(shù)據(jù)。

測(cè)試

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

歡迎訪問我的博客http://zxuqian.cn/spring-cloud-tutorial-hystrix/

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI