1. 程式人生 > >Spring Cloud入門教程之斷路器 Hystrix(四)(Finchley版本+Boot2.0)

Spring Cloud入門教程之斷路器 Hystrix(四)(Finchley版本+Boot2.0)

什麼是Hystrix?

Hystrix是Netflix開源的一款容錯框架,包含常用的容錯方法:執行緒隔離、訊號量隔離、降級策略、熔斷技術。在高併發訪問下,系統所依賴的服務的穩定性對系統的影響非常大,依賴有很多不可控的因素,比如網路連線變慢,資源突然繁忙,暫時不可用,服務離線等。我們要構建穩定、可靠的分散式系統,就必須要有這樣一套容錯方法。

為什麼使用Hystrix?

在微服務架構中,根據業務來拆分成一個個的服務,服務與服務之間可以相互呼叫(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign來呼叫。為了保證其高可用,單個服務通常會叢集部署。由於網路原因或者自身的原因,服務並不能保證100%可用,如果單個服務出現問題,呼叫這個服務就會出現執行緒阻塞,此時若有大量的請求湧入,Servlet容器的執行緒資源會被消耗完畢,導致服務癱瘓。服務與服務之間的依賴性,故障會傳播,會對整個微服務系統造成災難性的嚴重後果,這就是服務故障的“雪崩”效應。

舉個例子:

比如我們現在有3個業務呼叫分別是查詢訂單、查詢商品、查詢使用者,且這三個業務請求都是依賴第三方服務-訂單服務、商品服務、使用者服務。三個服務均是通過RPC呼叫。當查詢訂單服務,假如執行緒阻塞了,這個時候後續有大量的查詢訂單請求過來,那麼容器中的執行緒數量則會持續增加直致CPU資源耗盡到100%,整個服務對外不可用,叢集環境下就是雪崩。

推薦部落格:

Spring cloud系列十 使用@HystrixCommand使用Hystrix元件及@EnableCircuitBreaker原理介紹

為了解決這個問題,業界提出了斷路器模型。Netflix開源了Hystrix元件,實現了斷路器模式,SpringCloud對這一元件進行了整合。 在微服務架構中,一個請求需要呼叫多個服務是非常常見的,如下圖:

較底層的服務如果出現故障,會導致連鎖故障。當對特定的服務的呼叫的不可用達到一個閥值(Hystric 是5秒20次) 斷路器將會被開啟。

斷路開啟後,可用避免連鎖故障,fallback方法可以直接返回一個固定值。

在Ribbon使用斷路器遇到的錯誤:由於Spring Boot 2.0 整合Cloud找不到@HystrixCommand註解,下面是原始碼和錯誤

解決方案

新增pom.xml

<dependency>
   <groupId>com.netflix.hystrix</groupId>
   <artifactId>hystrix-javanica</artifactId>
   <version>RELEASE</version>
</dependency>

原始碼:

下面將介紹在Ribbon和Feign中使用斷路器

一、在Ribbon使用斷路器

1、修改pom.xml

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

      <dependency>
         <groupId>com.netflix.hystrix</groupId>
         <artifactId>hystrix-javanica</artifactId>
         <version>RELEASE</version>
      </dependency>

完整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>com.serverribbon</groupId>
   <artifactId>serverribbon</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>serverribbon</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Finchley.RC2</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
      </dependency>

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

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

      <dependency>
         <groupId>com.netflix.hystrix</groupId>
         <artifactId>hystrix-javanica</artifactId>
         <version>RELEASE</version>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>com.netflix.hystrix</groupId>
         <artifactId>hystrix-core</artifactId>
         <version>RELEASE</version>
      </dependency>
        <dependency>
            <groupId>com.netflix.hystrix</groupId>
            <artifactId>hystrix-core</artifactId>
            <version>RELEASE</version>
        </dependency>
    </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</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/milestone</url>
         <snapshots>
            <enabled>false</enabled>
         </snapshots>
      </repository>
   </repositories>


</project>

2、改造HelloService類,在hiService方法上加上@HystrixCommand註解。該註解對該方法建立了熔斷器的功能,並指定了fallbackMethod熔斷方法,熔斷方法直接返回了一個字串,字串為”hi,”+name+”,走了熔斷方法!”,程式碼如下:

package com.cloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloError")
    public String hiService(String name) {
        return restTemplate.getForObject("http://HELLO-SERVICE/hi?name=" + name, String.class);
    }

    public String helloError(String name) {
        return "hello," + name + ",走了熔斷方法!";
    }
}

3、在程式的啟動類ServiceRibbonApplication 加@EnableHystrix註解開啟Hystrix

package com.serverribbon.serverribbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan("com.cloud.*")
@EnableHystrix
public class ServerribbonApplication {

   public static void main(String[] args) {
      SpringApplication.run(ServerribbonApplication.class, args);
   }


   @Bean
   @LoadBalanced
   RestTemplate restTemplate() {
      return new RestTemplate();
   }
}

4、啟動服務註冊中心、服務提供者(1個)、服務消費者(Ribbon)

5、消費服務、停止服務提供者提供檢視效果

消費服務

停止服務提供後消費

這就說明當 service-hi 工程不可用的時候,service-ribbon呼叫 service-hi的API介面時,會執行快速失敗,直接返回一組字串,而不是等待響應超時,這很好的控制了容器的執行緒阻塞。

二、在Feign使用斷路器

1、修改配置檔案

注:Feign是自帶斷路器的,在D版本的Spring Cloud中,它沒有預設開啟。需要在配置檔案中配置開啟即可。

server.port=8765
spring.application.name=service-feign
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
feign.hystrix.enabled=true

2、只需要在HelloService介面的註解中加上fallback的指定類

package com.serverfeign.serverfeign.service;

import org.springframework.stereotype.Component;

@Component
public class SchedualServiceHiHystric implements HelloService{
    @Override
    public String sayHiFromClientOne(String name) {
        return "走了feign自帶的熔斷方法!!";
    }
}

package com.serverfeign.service;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by zhoujh on 2018/6/4.
 */
@FeignClient(value = "hello-service",fallback = SchedualServiceHiHystric.class)
public interface HelloService {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}


3、啟動服務註冊中心、服務提供者(1個)、服務消費者(Feign)

4、消費服務、停止服務提供者提供檢視效果

消費服務

停止服務提供後消費

Spring Boot與Spring Cloud學習使用可參看筆者部落格