SpringCloud(三)--Hystrix

Hystrix 斷路器

系統容錯工具html

  • 降級java

    • 調用遠程服務失敗(宕機、500錯、超時),能夠降級執行當前服務中的一段代碼,向客戶端返回結果
    • 快速失敗
  • 熔斷git

    • 當訪問量過大,出現大量失敗,能夠作過熱保護,斷開遠程服務再也不調用
    • 限流
    • 防止故障傳播、雪崩效應
  • https://github.com/Netflix/Hystrix/wiki
    hystrix

Hystrix

Hystrix降級

  1. hystrix依賴
  2. 啓動類添加註解 @EnableCircuitBreaker
  3. 添加降級代碼
// 當調用遠程服務失敗,跳轉到指定的方法,執行降級代碼
@HystrixCommand(fallbackMethod="方法名")
遠程調用方法() {
 restTemplate.getForObject(url,......);
}

微服務宕機時,ribbon 沒法轉發請求

  • 關閉 user-service 和 order-service

關閉
白板
說明:這是沒有hystrix的狀況,下來測試hystrix提供的降級處理方式github

複製 sp06-ribbon 項目,命名爲sp07-hystrix

  • 選擇 sp06-ribbon 項目,ctrl-c,ctrl-v,複製爲sp07-hystrix
  • 關閉 sp06-ribbon 項目,後續測試使用 sp07-hystrix 項目

複製項目

修改 pom.xml

修改pom

添加 hystrix 起步依賴

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

修改 application.yml

修改yml

spring:
  application:
    name: hystrix
    
server:
  port: 3001
  
eureka:
  client:    
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
      
ribbon:
  MaxAutoRetries: 1
  MaxAutoRetriesNextServer: 2
  OkToRetryOnAllOperations: true

主程序添加 @EnableCircuitBreaker 啓用 hystrix 斷路器

啓動斷路器,斷路器提供兩個核心功能:web

  • 降級,超時、出錯、不可到達時,對服務降級,返回錯誤信息或者是緩存數據
  • 熔斷,當服務壓力過大,錯誤比例過多時,熔斷全部請求,全部請求直接降級
  • 可使用 @SpringCloudApplication 註解代替三個註解
package cn.tedu.sp06;

import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

//@EnableCircuitBreaker
//@EnableDiscoveryClient
//@SpringBootApplication

@SpringCloudApplication
public class Sp06RibbonApplication {

    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate() {
        SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
        f.setConnectTimeout(1000);
        f.setReadTimeout(1000);
        return new RestTemplate(f);
        
        //RestTemplate 中默認的 Factory 實例中,兩個超時屬性默認是 -1,
        //未啓用超時,也不會觸發重試
        //return new RestTemplate();
    }

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

}

RibbonController 中添加降級方法

  • 爲每一個方法添加降級方法,例如 getItems() 添加降級方法 getItemsFB()
  • 添加 @HystrixCommand 註解,指定降級方法名
package cn.tedu.sp06.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@Slf4j
public class RibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "getItemsFB") //指定降級方法的方法名
    @GetMapping("/item-service/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId){
        //遠程調用商品服務
        //http://localhost:8001/{orderId}
        //{1} -- RestTemplate 定義的一種佔位符格式,傳遞參數orderId
        //return restTemplate.getForObject("http://localhost:8001/{1}",JsonResult.class,orderId);
        return restTemplate.getForObject("http://item-service/{1}",JsonResult.class,orderId);//Ribbon的方式,將ip:port改成服務名稱
    }

    @HystrixCommand(fallbackMethod = "decreaseNumberFB") //指定降級方法的方法名
    @PostMapping("/item-service/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        return restTemplate.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
    }

    // -----------------------

    @HystrixCommand(fallbackMethod = "getUserFB") //指定降級方法的方法名
    @GetMapping("/user-service/{userId}")
    public JsonResult<User> getUser(@PathVariable Integer userId){
        return restTemplate.getForObject("http://user-service/{1}", JsonResult.class,userId);
    }
    @HystrixCommand(fallbackMethod = "addScoreFB") //指定降級方法的方法名
    @GetMapping("/user-service/{userId}/score")
    public JsonResult<?> addScore(@PathVariable Integer userId,Integer score){
        return restTemplate.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class,userId,score);
    }
    @HystrixCommand(fallbackMethod = "getOrderFB") //指定降級方法的方法名
    @GetMapping("/order-service/{orderId}")
    public JsonResult<Order> getOrder(@PathVariable String orderId){
        return restTemplate.getForObject("http://order-service/{1}", JsonResult.class,orderId);
    }
    @HystrixCommand(fallbackMethod = "addOrderFB") //指定降級方法的方法名
    @GetMapping("/order-service/")
    public JsonResult<?> addOrder(){
        return restTemplate.getForObject("http://order-service/", JsonResult.class);
    }


    // -----------------------

    //降級方法的參數和返回值,須要和原始方法一致,方法名任意
    public JsonResult<List<Item>> getItemsFB(String orderId){
        return JsonResult.err("獲取訂單商品列表失敗");
    }
    public JsonResult<?> decreaseNumberFB(List<Item> items){
        return JsonResult.err("更新商品庫存失敗");
    }
    public JsonResult<User> getUserFB(Integer userId){
        return JsonResult.err("獲取用戶信息失敗");
    }
    public JsonResult<?> addScoreFB(Integer userId,Integer score){
        return JsonResult.err("增長用戶積分失敗");
    }
    public JsonResult<Order> getOrderFB(String orderId){
        return JsonResult.err("獲取訂單失敗");
    }
    public JsonResult<?> addOrderFB(){
        return JsonResult.err("添加訂單失敗");
    }
}

hystrix 超時設置

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix等待超時後, 會執行降級代碼, 快速向客戶端返回降級結果, 默認超時時間是1000毫秒
爲了測試 hystrix 降級,咱們把 hystrix 等待超時設置得很是小(1000毫秒)
此設置通常應大於 ribbon 的重試超時時長,例如 10 秒spring

spring:
  application:
    name: hystrix

server:
  port: 3001

eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka

# 配置 Ribbon 重試次數
ribbon:
  # 次數參數沒有提示,而且會有黃色警告
  # 重試次數越少越好,通常建議用0 ,1
  MaxAutoRetries: 1
  MaxAutoRetriesNextServer: 2

#配置hystrix超時設置 快速向客戶端返回降級結果, 默認超時時間是1000毫秒
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000

啓動項目進行測試

啓動測試

  • 經過 hystrix 服務,訪問可能超時失敗的 item-service
    http://localhost:3001/item-service/35
  • 經過 hystrix 服務,訪問未啓動的 user-service
    http://localhost:3001/user-service/7
  • 能夠看到,若是 item-service 請求超時,hystrix 會當即執行降級方法
  • 訪問 user-service,因爲該服務未啓動,hystrix也會當即執行降級方法

降級

hystrix dashboard 斷路器儀表盤

dashboard

hystrix 對請求的降級和熔斷,能夠產生監控信息,hystrix dashboard能夠實時的進行監控shell

Actuator

springboot 提供的日誌監控工具,能夠暴露項目中多種監控信息apache

  • 健康狀態
  • 系統環境變量
  • spring容器中全部的對象
  • spring mvc映射的全部路徑
  • ......

添加 actuatorwindows

  1. 添加 actuator 依賴
  2. yml 配置暴露監控數據緩存

    • m.e.w.e.i="*" 暴露全部的監控
    • m.e.w.e.i=health 只暴露健康狀態
    • m.e.w.e.i=["health", "beans", "mappings"] 暴露指定的多個監控

sp07-hystrix 項目添加 actuator,並暴露 hystrix 監控端點

actuator 是 spring boot 提供的服務監控工具,提供了各類監控信息的監控端點
management.endpoints.web.exposure.include 配置選項,
能夠指定端點名,來暴露監控端點
若是要暴露全部端點,能夠用 「*」
Actuator

pom.xml 添加 actuator 依賴

右鍵點擊項目或pom.xml, 編輯起步依賴, 添加 actuator 依賴
編輯起步依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

調整 application.yml 配置,並暴露 hystrix.stream 監控端點

spring:
  application:
    name: hystrix

server:
  port: 3001

eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka

# 配置 Ribbon 重試次數
ribbon:
  # 次數參數沒有提示,而且會有黃色警告
  # 重試次數越少越好,通常建議用0 ,1
  MaxAutoRetries: 1
  MaxAutoRetriesNextServer: 2

#配置hystrix超時設置 快速向客戶端返回降級結果, 默認超時時間是1000毫秒
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000
#配置actuator,暴露hystrix.stream監控端點
management:
  endpoints:
    web:
      exposure:
        include: "*"

訪問 actuator 路徑,查看監控端點

actuator

Hystrix dashboard 儀表盤

搭建 Hystrix Dashboard

儀表盤項目能夠是一個徹底獨立的項目,與其餘項目都無關,也不用向註冊表註冊

  1. hystrix dashboard 依賴
  2. @EnableHystrixDashboard
  3. yml - 容許對哪臺服務器開啓監控
hystrix:
 dashboard:
 proxy-stream-allow-list: localhost

dashboard

新建 sp08-hystrix-dashboard 項目

新建項目

添加依賴

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.tedu</groupId>
    <artifactId>sp08-hystrix-dashboard</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sp08-hystrix-dashboard</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.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-netflix-hystrix-dashboard</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </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>

</project>

application.yml

spring:
  application:
    name: hystrix-dashboard
    
server:
  port: 4001

eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka

hystrix:
  dashboard:
    proxy-stream-allow-list: localhost

主程序添加 @EnableHystrixDashboard@EnableDiscoveryClient

package cn.tedu.sp08;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@EnableDiscoveryClient
@EnableHystrixDashboard
@SpringBootApplication
public class Sp08HystrixDashboardApplication {

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

啓動,並訪問測試

啓動訪問測試

訪問 hystrix dashboard

dashboard

填入 hystrix 的監控端點,開啓監控

開啓監控

  • 經過 hystrix 訪問服務屢次,觀察監控信息

http://localhost:3001/item-service/35

http://localhost:3001/user-service/7
http://localhost:3001/user-service/7/score?score=100

http://localhost:3001/order-service/123abc
http://localhost:3001/order-service/

監控界面

監控界面

Hystrix 熔斷

短路器打開的條件:

  • 10秒內20次請求(必須首先知足)
  • 50%失敗,執行了降級代碼
短路器打開後,全部請求直接執行降級代碼
斷路器打開幾秒後,會進入**半開狀態**,客戶端調用會嘗試向後臺服務發送一次調用,
若是調用成功,斷路器能夠自動關閉,恢復正常
若是調用仍然失敗,繼續保持打開狀態幾秒鐘

整個鏈路達到必定的閾值,默認狀況下,10秒內產生超過20次請求,則符合第一個條件。
知足第一個條件的狀況下,若是請求的錯誤百分比大於閾值,則會打開斷路器,默認爲50%。
Hystrix的邏輯,先判斷是否知足第一個條件,再判斷第二個條件,若是兩個條件都知足,則會開啓斷路器

斷路器打開 5 秒後,會處於半開狀態,會嘗試轉發請求,若是仍然失敗,保持打開狀態,若是成功,則關閉斷路器

使用 apache 的併發訪問測試工具 ab

http://httpd.apache.org/docs/current/platform/windows.html#down
下載Apache

  • 用 ab 工具,以併發50次,來發送20000個請求
ab -n 20000 -c 50 http://localhost:3001/item-service/35
  • 斷路器狀態爲 Open,全部請求會被短路,直接降級執行 fallback 方法

熔斷

Hystrix 配置

https://github.com/Netflix/Hystrix/wiki/Configuration

  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
    請求超時時間,超時後觸發失敗降級
  • hystrix.command.default.circuitBreaker.requestVolumeThreshold
    10秒內請求數量,默認20,若是沒有達到該數量,即便請求所有失敗,也不會觸發斷路器打開
  • hystrix.command.default.circuitBreaker.errorThresholdPercentage
    失敗請求百分比,達到該比例則觸發斷路器打開
  • hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds斷路器打開多長時間後,再次容許嘗試訪問(半開),仍失敗則繼續保持打開狀態,如成功訪問則關閉斷路器,默認 5000
相關文章
相關標籤/搜索