SpringCloud(第 015 篇)電影Ribbon微服務(wù)集成Hystrix增加隔離策略控制線程數(shù)或請求數(shù)來達(dá)到熔斷降級的作用

SpringCloud(第 015 篇)電影Ribbon微服務(wù)集成Hystrix增加隔離策略控制線程數(shù)或請求數(shù)來達(dá)到熔斷降級的作用

一、大致介紹

1、本章節(jié)介紹關(guān)于Hystrix的2種隔離方式(Thread Pool 和 Semaphores);
2、ThreadPool:這是比較常用的隔離策略,即根據(jù)配置把不同的命令分配到不同的線程池中,該策略的優(yōu)點是隔離性好,并且可以配置斷路,某個依賴被設(shè)置斷路之后,系統(tǒng)不會再嘗試新起線程運行它,而是直接提示失敗,或返回fallback值;缺點是新起線程執(zhí)行命令,在執(zhí)行的時候必然涉及到上下文的切換,這會造成一定的性能消耗,但是Netflix做過實驗,這種消耗對比其帶來的價值是完全可以接受的。
3、Semaphores:開發(fā)者可以限制系統(tǒng)對某一個依賴的最高并發(fā)數(shù)。這個基本上就是一個限流的策略。每次調(diào)用依賴時都會檢查一下是否到達(dá)信號量的限制值,如達(dá)到,則拒絕。該隔離策略的優(yōu)點不新起線程執(zhí)行命令,減少上下文切換,缺點是無法配置斷路,每次都一定會去嘗試獲取信號量。 
4、而本章節(jié)主要簡單的介紹下如何使用 Semaphores 來達(dá)到控制隔離;

二、實現(xiàn)步驟

2.1 添加 maven 引用包

<?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>

    <artifactId>springms-consumer-movie-ribbon-with-hystrix-propagation</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <parent>
        <groupId>com.springms.cloud</groupId>
        <artifactId>springms-spring-cloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    
    <dependencies>
        <!-- web模塊 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 客戶端發(fā)現(xiàn)模塊 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <!-- Hystrix 斷路器模塊 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
    </dependencies>

</project>

2.2 添加應(yīng)用配置文件(springms-consumer-movie-ribbon-with-hystrix-propagation\src\main\resources\application.yml)

spring:
  application:
    name: springms-consumer-movie-ribbon-with-hystrix-propagation
server:
  port: 8100
#做負(fù)載均衡的時候,不需要這個動態(tài)配置的地址
#user:
#  userServicePath: http://localhost:7900/simple/
eureka:
  client:
#    healthcheck:
#      enabled: true
    serviceUrl:
      defaultZone: http://admin:admin@localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}


# 解決第一次請求報超時異常的方案,因為 hystrix 的默認(rèn)超時時間是 1 秒,因此請求超過該時間后,就會出現(xiàn)頁面超時顯示 :
#
# 這里就介紹大概三種方式來解決超時的問題,解決方案如下:
#
# 第一種方式:將 hystrix 的超時時間設(shè)置成 5000 毫秒
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
#
# 或者:
# 第二種方式:將 hystrix 的超時時間直接禁用掉,這樣就沒有超時的一說了,因為永遠(yuǎn)也不會超時了
# hystrix.command.default.execution.timeout.enabled: false
#
# 或者:
# 第三種方式:索性禁用feign的hystrix支持
# feign.hystrix.enabled: false ## 索性禁用feign的hystrix支持

# 超時的issue:https://github.com/spring-cloud/spring-cloud-netflix/issues/768
# 超時的解決方案: http://stackoverflow.com/questions/27375557/hystrix-command-fails-with-timed-out-and-no-fallback-available
# hystrix配置: https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.thread.timeoutInMilliseconds

2.3 添加實體用戶類User(springms-consumer-movie-ribbon-with-hystrix-propagation\src\main\java\com\springms\cloud\entity\User.java)

package com.springms.cloud.entity;

import java.math.BigDecimal;

public class User {

    private Long id;

    private String username;

    private String name;

    private Short age;

    private BigDecimal balance;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Short getAge() {
        return this.age;
    }

    public void setAge(Short age) {
        this.age = age;
    }

    public BigDecimal getBalance() {
        return this.balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

}

2.4 添加電影Web訪問層Controller(springms-consumer-movie-ribbon-with-hystrix-propagation\src\main\java\com\springms\cloud\controller\MovieRibbonHystrixPropagationController.java)

package com.springms.cloud.controller;

import com.springms.cloud.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class MovieRibbonHystrixPropagationController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/movie/{id}")
    @HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties = @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"))
    public User findById(@PathVariable Long id) {
        // http://localhost:7900/simple/
        // VIP:virtual IP
        // HAProxy Heartbeat

        System.out.println("======================== findById " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());

        return this.restTemplate.getForObject("http://springms-provider-user/simple/" + id, User.class);
    }

    public User findByIdFallback(Long id) {
        System.out.println("======================== findByIdFallback " + Thread.currentThread().getThreadGroup() + " - " + Thread.currentThread().getId() + " - " + Thread.currentThread().getName());

        User user = new User();
        user.setId(0L);
        return user;
    }
}

2.5 添加電影微服務(wù)啟動類(springms-consumer-movie-ribbon-with-hystrix-propagation\src\main\java\com\springms\cloud\MsConsumerMovieRibbonHystrixPropagationApplication.java)

package com.springms.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * 電影Ribbon微服務(wù)集成Hystrix增加隔離策略控制線程數(shù)或請求數(shù)來達(dá)到熔斷降級的作用。
 *
 * 傳播安全上下文或使用,通過增加 HystrixCommand 的 commandProperties 屬性,來增加相關(guān)的配置來達(dá)到執(zhí)行隔離策略,控制線程數(shù)或者控制并發(fā)請求數(shù)來達(dá)到熔斷降級的作用。
 *
 * Hystrix 斷路器實現(xiàn)失敗快速響應(yīng),達(dá)到熔斷效果;
 *
 * 注解 EnableCircuitBreaker 表明需要集成斷路器模塊;
 *
 * 如果你想把本地線程上下文傳播到@HystrixCommand,默認(rèn)的聲明將不可用因為它是在一個線程池中被啟動的。你可以選擇讓Hystrix使用同一個線程,通過一些配置,或直接寫在注解上,通過使用isolation strategy屬性;
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017/9/21
 *
 */
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class MsConsumerMovieRibbonHystrixPropagationApplication {

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

    public static void main(String[] args) {
        SpringApplication.run(MsConsumerMovieRibbonHystrixPropagationApplication.class, args);
        System.out.println("【【【【【【 電影微服務(wù)-Hystrix安全傳播上下文 】】】】】】已啟動.");
    }
}

三、測試

/****************************************************************************************
 一、電影 Ribbon 微服務(wù)集成 Hystrix 斷路器實現(xiàn)失敗快速響應(yīng),達(dá)到熔斷效果:

 1、注解:EnableCircuitBreaker、HystrixCommand 的編寫;
 2、啟動 springms-provider-user 模塊服務(wù),啟動1個端口;
 3、啟動 springms-consumer-movie-ribbon-with-hystrix-propagation 模塊服務(wù);
 4、在瀏覽器輸入地址http://localhost:8100/movie/1,然后頁面的信息是否有打印出來用戶的Id=0的情況,正常情況下是沒有用戶Id=0的情況信息打印的;

 5、殺死 springms-provider-user 模塊服務(wù),停止提供服務(wù);
 6、在瀏覽器輸入地址http://localhost:8100/movie/1,然后頁面的信息是否有打印出來用戶的Id=0的情況,等了1秒中后有用戶Id=0的情況信息打印出來;
 7、然后看看控制臺打印的日志:
     ======================== findById java.lang.ThreadGroup[name=main,maxpri=10] - 56 - http-nio-8100-exec-8
     ======================== findByIdFallback java.lang.ThreadGroup[name=main,maxpri=10] - 56 - http-nio-8100-exec-8
     ======================== findById java.lang.ThreadGroup[name=main,maxpri=10] - 57 - http-nio-8100-exec-9
     ======================== findByIdFallback java.lang.ThreadGroup[name=main,maxpri=10] - 57 - http-nio-8100-exec-9
     ======================== findById java.lang.ThreadGroup[name=main,maxpri=10] - 35 - http-nio-8100-exec-1
     ======================== findByIdFallback java.lang.ThreadGroup[name=main,maxpri=10] - 35 - http-nio-8100-exec-1

 總結(jié)一:使用 SEMAPHORE 信號量的時候,雖然不能配置斷路器功能,但是通過控制請求數(shù)來達(dá)到一個限流的作用;

 8、等一會兒在啟動 springms-provider-user 模塊服務(wù),啟動1個端口;
 9、在瀏覽器輸入地址http://localhost:8070/movie/1,然后頁面的信息又有Id!=0的用戶信息打印出來;

 總結(jié)二:當(dāng)遠(yuǎn)端微服務(wù)宕機或者不可用時,Hystrix已經(jīng)達(dá)到快速響應(yīng)快速失敗,起到了熔斷機制的效果。
 ****************************************************************************************/







/****************************************************************************************
 找出一些相關(guān)的配置信息僅供參考:

 Execution相關(guān)的屬性的配置:
 hystrix.command.default.execution.isolation.strategy 隔離策略,默認(rèn)是Thread, 可選Thread|Semaphore
     thread 通過線程數(shù)量來限制并發(fā)請求數(shù),可以提供額外的保護(hù),但有一定的延遲。一般用于網(wǎng)絡(luò)調(diào)用
     semaphore 通過semaphore count來限制并發(fā)請求數(shù),適用于無網(wǎng)絡(luò)的高并發(fā)請求
 hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令執(zhí)行超時時間,默認(rèn)1000ms
 hystrix.command.default.execution.timeout.enabled 執(zhí)行是否啟用超時,默認(rèn)啟用true
 hystrix.command.default.execution.isolation.thread.interruptOnTimeout 發(fā)生超時是是否中斷,默認(rèn)true
 hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 最大并發(fā)請求數(shù),默認(rèn)10,該參數(shù)當(dāng)使用ExecutionIsolationStrategy.SEMAPHORE策略時才有效。如果達(dá)到最大并發(fā)請求數(shù),請求會被拒絕。理論上選擇semaphore size的原則和選擇thread size一致,但選用semaphore時每次執(zhí)行的單元要比較小且執(zhí)行速度快(ms級別),否則的話應(yīng)該用thread。
 semaphore應(yīng)該占整個容器(tomcat)的線程池的一小部分。

 Fallback相關(guān)的屬性:
 這些參數(shù)可以應(yīng)用于Hystrix的THREAD和SEMAPHORE策略
 hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests 如果并發(fā)數(shù)達(dá)到該設(shè)置值,請求會被拒絕和拋出異常并且fallback不會被調(diào)用。默認(rèn)10
 hystrix.command.default.fallback.enabled 當(dāng)執(zhí)行失敗或者請求被拒絕,是否會嘗試調(diào)用hystrixCommand.getFallback() 。默認(rèn)true
 Circuit Breaker相關(guān)的屬性
 hystrix.command.default.circuitBreaker.enabled 用來跟蹤circuit的健康性,如果未達(dá)標(biāo)則讓request短路。默認(rèn)true
 hystrix.command.default.circuitBreaker.requestVolumeThreshold 一個rolling window內(nèi)最小的請求數(shù)。如果設(shè)為20,那么當(dāng)一個rolling window的時間內(nèi)(比如說1個rolling window是10秒)收到19個請求,即使19個請求都失敗,也不會觸發(fā)circuit break。默認(rèn)20
 hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds 觸發(fā)短路的時間值,當(dāng)該值設(shè)為5000時,則當(dāng)觸發(fā)circuit break后的5000毫秒內(nèi)都會拒絕request,也就是5000毫秒后才會關(guān)閉circuit。默認(rèn)5000
 hystrix.command.default.circuitBreaker.errorThresholdPercentage錯誤比率閥值,如果錯誤率>=該值,circuit會被打開,并短路所有請求觸發(fā)fallback。默認(rèn)50
 hystrix.command.default.circuitBreaker.forceOpen 強制打開熔斷器,如果打開這個開關(guān),那么拒絕所有request,默認(rèn)false
 hystrix.command.default.circuitBreaker.forceClosed 強制關(guān)閉熔斷器 如果這個開關(guān)打開,circuit將一直關(guān)閉且忽略circuitBreaker.errorThresholdPercentage

 Metrics相關(guān)參數(shù):
 hystrix.command.default.metrics.rollingStats.timeInMilliseconds 設(shè)置統(tǒng)計的時間窗口值的,毫秒值,circuit break 的打開會根據(jù)1個rolling window的統(tǒng)計來計算。若rolling window被設(shè)為10000毫秒,則rolling window會被分成n個buckets,每個bucket包含success,failure,timeout,rejection的次數(shù)的統(tǒng)計信息。默認(rèn)10000
 hystrix.command.default.metrics.rollingStats.numBuckets 設(shè)置一個rolling window被劃分的數(shù)量,若numBuckets=10,rolling window=10000,那么一個bucket的時間即1秒。必須符合rolling window % numberBuckets == 0。默認(rèn)10
 hystrix.command.default.metrics.rollingPercentile.enabled 執(zhí)行時是否enable指標(biāo)的計算和跟蹤,默認(rèn)true
 hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds 設(shè)置rolling percentile window的時間,默認(rèn)60000
 hystrix.command.default.metrics.rollingPercentile.numBuckets 設(shè)置rolling percentile window的numberBuckets。邏輯同上。默認(rèn)6
 hystrix.command.default.metrics.rollingPercentile.bucketSize 如果bucket size=100,window=10s,若這10s里有500次執(zhí)行,只有最后100次執(zhí)行會被統(tǒng)計到bucket里去。增加該值會增加內(nèi)存開銷以及排序的開銷。默認(rèn)100
 hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds 記錄health 快照(用來統(tǒng)計成功和錯誤綠)的間隔,默認(rèn)500ms

 Request Context 相關(guān)參數(shù):
 hystrix.command.default.requestCache.enabled 默認(rèn)true,需要重載getCacheKey(),返回null時不緩存
 hystrix.command.default.requestLog.enabled 記錄日志到HystrixRequestLog,默認(rèn)true

 Collapser Properties 相關(guān)參數(shù):
 hystrix.collapser.default.maxRequestsInBatch 單次批處理的最大請求數(shù),達(dá)到該數(shù)量觸發(fā)批處理,默認(rèn)Integer.MAX_VALUE
 hystrix.collapser.default.timerDelayInMilliseconds 觸發(fā)批處理的延遲,也可以為創(chuàng)建批處理的時間+該值,默認(rèn)10
 hystrix.collapser.default.requestCache.enabled 是否對HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默認(rèn)true

 ThreadPool 相關(guān)參數(shù):
 線程數(shù)默認(rèn)值10適用于大部分情況(有時可以設(shè)置得更小),如果需要設(shè)置得更大,那有個基本得公式可以follow:
 requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room
 每秒最大支撐的請求數(shù) (99%平均響應(yīng)時間 + 緩存值)
 比如:每秒能處理1000個請求,99%的請求響應(yīng)時間是60ms,那么公式是:
 1000 (0.060+0.012)

 ****************************************************************************************/

四、下載地址

https://gitee.com/ylimhhmily/SpringCloudTutorial.git

SpringCloudTutorial交流QQ群: 235322432

SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接

歡迎關(guān)注,您的肯定是對我最大的支持!!!

<上一篇????????首頁????????下一篇>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容