SpringCloud之Hystrix的詳細使用

1.概念

服務降級:服務器繁忙,請稍後再試,不讓客戶端等待,並立即返回一個友好的提示(一般發生在 程序異常,超時,服務熔斷觸發服務降級,線程池、信號量 打滿也會導致服務降級)
服務熔斷 : 達到最大服務訪問後,直接拒絕訪問,然後調用服務降級的方法並返回友好提示(如保險絲一樣)
服務限流 : 秒殺等高並發操作,嚴禁一窩蜂的過來擁擠,排隊進入,一秒鐘N個,有序進行

***一.服務降級***

2.不使用Hystrix的項目

大致的Service和Controller層如下

***************Controller*****************
package com.sky.springcloud.controller;

import com.sky.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverport;
    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_Ok(@PathVariable("id") Integer id){
        String result = paymentService.paymentInfo_ok(id);
        log.info("*****"+ result);
        return result;
    }
    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
        String result = paymentService.payment_Info_TimeOut(id);
}
*******************Service******************** 
package com.sky.springcloud.service;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class PaymentServiceImpl implements PaymentService{
    @Override
    public String paymentInfo_ok(Integer id) {
        return "線程池:" + Thread.currentThread().getName() + "paymentInfo_Ok. id:" + id + "\t" + "~~~~~";
    public String payment_Info_TimeOut(Integer id) {
       try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "線程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut. id:" + id + "\t" + "~~~~~";

在這種情況時,當通過瀏覽器訪問 TimeOut這個方法,會三秒後返回結果,而當訪問 OK 這個方法時,會直接返回結果(但是這是在訪問量很少的時候,一旦訪問量過多,訪問OK時也會出現延遲,這裡可以使用Jmeter模擬兩萬個訪問量,如下)

在這裡插入圖片描述

在這裡插入圖片描述

使用 Jmeter 模擬後,再去訪問OK,會明顯出現加載的效果

3. 使用Hystrix

在主啟動類添加註解
@EnableHystrix

package com.sky.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
@SpringBootApplication
@EnableEurekaClient //啟用Eureka
@EnableHystrix     //啟用Hystrix
public class Payment8001 {
    public static void main(String[] args) {
        SpringApplication.run(Payment8001.class,args);
    }
}

在原有的基礎上,在Service層加上如下註解

 @HystrixCommand(fallbackMethod = "payment_Info_TimeOutHandler",//當服務降級時,調用payment_Info_TimeOutHandler方法
                  commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
            value = "3000")//設置時間為3秒,超過三秒就為時間超限
*****************改後的Service*******************
package com.sky.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
@Service
public class PaymentServiceImpl implements PaymentService{
    @Override
    public String paymentInfo_ok(Integer id) {
        return "線程池:" + Thread.currentThread().getName() + "paymentInfo_Ok. id:" + id + "\t" + "~~~~~";
    }

    @HystrixCommand(fallbackMethod = "payment_Info_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String payment_Info_TimeOut(Integer id) {
      try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
      // int a = 10 / 0;
        return "線程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut. id:" + id + "\t" + "~~~~~";
    }
    public String payment_Info_TimeOutHandler(Integer id){
        return "線程超時或異常 " + Thread.currentThread().getName();
    }
}

如上Service所示,如果再次訪問TimeOut需要等待五秒,但是Hystrix設置的超時時間為三秒,所以當三秒後沒有結果就會服務降級,從而調用TimeOutHandler這個指定 的方法來執行(或者有程序出錯等情況也會服務降級)

4. 全局的Hystrix配置

@DefaultProperties(defaultFallback = “Gloub_Test”)

package com.sky.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
@Service
@DefaultProperties(defaultFallback = "Gloub_Test")
public class PaymentServiceImpl implements PaymentService{
    @Override
    @HystrixCommand
    public String paymentInfo_ok(Integer id) {
        int a = 10 / 0;
        return "線程池:" + Thread.currentThread().getName() + "paymentInfo_Ok. id:" + id + "\t" + "~~~~~";
    }
    @HystrixCommand(fallbackMethod = "payment_Info_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String payment_Info_TimeOut(Integer id) {
   /*     try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        return "線程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut. id:" + id + "\t" + "~~~~~";
    public String payment_Info_TimeOutHandler(Integer id){
        return "線程超時或異常 " + Thread.currentThread().getName();
    public String Gloub_Test(){
        return "走瞭全局的";
}

如上Service所示,加瞭@HystrixCommand的方法裡,
如果沒指定fallbackMethod 就會默認去找全局的defaultFallback
這裡 當paymentInfo_ok 方法出錯時,會調用Gloub_Test方法
當payment_Info_TimeOut出錯時,會調用payment_Info_TimeOutHandler方法

 ***二.服務熔斷***

1.熔斷機制概述

熔斷機制是應對雪崩效應的一種微服務鏈路保護機制,當扇出鏈路的某個微服務出錯不可用或者響應時間太長,會進行服務的降級,進而熔斷該節點微服務的調用,快速返回錯誤的相應信息.當檢測到該節點微服務調用相應正常後,恢復調用鏈路.

2.項目中使用

在上面的基礎上,改寫Service和Controller(添加以下代碼)

//是否開啟服務熔斷(斷路器)
 @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
 //服務請求的次數 
 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
 //時間的窗口期
 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
 //當失敗率達到多少後發生熔斷
 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), 

******************Service*****************
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",
                    commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
                    })
    public String PaymentCircuitBreaker(@PathVariable("id") Integer id){
        if(id<0){
            throw new RuntimeException("********** id不能為負");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return  "id 不能為負:" + id;
************Controller********************
    @GetMapping("/payment/circuit/{id}")
        String result = paymentService.PaymentCircuitBreaker(id);
        log.info(result + "***********");
        return result;

如上所示,當訪問paymentCircuitBreaker時,如果id小於零則會有一個運行錯誤,這時候就會通過服務降級來調用paymentCircuitBreaker_fallback方法,當錯誤的次數達到60%的時候(自己設的),就會出現服務熔斷,這個時候再訪問id大於零的情況,也會發生服務降級,因為開起瞭服務熔斷,需要慢慢的恢復正常.

到此這篇關於SpringCloud之Hystrix的詳細使用的文章就介紹到這瞭,更多相關SpringCloud Hystrix使用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: