• <noscript id="e0iig"><kbd id="e0iig"></kbd></noscript>
  • <td id="e0iig"></td>
  • <option id="e0iig"></option>
  • <noscript id="e0iig"><source id="e0iig"></source></noscript>
  • SpringCloud學習筆記(4):Hystrix容錯機制

    標簽: springcloud  histrix

    簡介

    在微服務架構中,微服務之間的依賴關系錯綜復雜,難免的某些服務會出現故障,導致服務調用方出現遠程調度的線程阻塞。在高負載的場景下,如果不做任何處理,可能會引起級聯故障,導致服務調用方的資源耗盡甚至整個系統奔潰。Hystrix是一個由Netflix開源的一個延遲和容錯庫,它通過添加延遲容忍和容錯邏輯來幫助控制這些微服務之間的交互。Hystrix通過隔離服務之間的訪問點、停止跨服務的級聯故障并提供回退選項來實現這一點,所有這些選項都提高了系統的總體彈性。

    項目介紹

    1. sc-parent,父模塊(請參照SpringCloud學習筆記(1):Eureka注冊中心)
    2. sc-eureka,注冊中心(請參照SpringCloud學習筆記(1):Eureka注冊中心)
    3. sc-provider,提供者(請參照SpringCloud學習筆記(1):Eureka注冊中心)
    4. sc-consumer-hystrix-ribbon,使用Hystrix+Ribbon的消費者
    5. sc-consumer-hystrix-feign,使用Hystrix+Feign的消費者

    在Ribbon上使用Hystrix

    1.在父模塊下創建子模塊項目sc-consumer-hystrix-ribbon,pom.xml:

    <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>
      <parent>
        <groupId>com.cf</groupId>
        <artifactId>sc-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
      </parent>
      <artifactId>sc-consumer-hystrix-ribbon</artifactId>
      
      <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</artifactId>
        </dependency>
      </dependencies>
    </project>

    2.創建啟動類consumer.ConsumerApplication:

    package consumer;
    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.context.annotation.Bean;
    import org.springframework.web.client.RestTemplate;
    
    @SpringBootApplication
    @EnableCircuitBreaker
    public class ConsumerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ConsumerApplication.class, args);
        }
        
        //為RestTemplate整合Ribbon,使其具備負載均衡的能力
        @LoadBalanced
        @Bean
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }

    3.創建調用提供者服務的Controller:consumer.controller.ConsumerController

    package consumer.controller;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    
    @RestController
    public class ConsumerController {
        @Autowired
        private RestTemplate restTemplate;
        
        @HystrixCommand(fallbackMethod="getBookListFallBack")
        @GetMapping("/getBookList")
        public String getBookList(){
            return restTemplate.getForObject("http://sc-provider/book/list", String.class);
        }
        
        public String getBookListFallBack(){
            return "[\"Java入門到放棄\"]";
        }
    }

    @HystrixCommand:表示將getBookList方法作為hystrix命令調用的方法。
    fallbackMethod:指定處理回退邏輯的方法,這里是getBookListFallBack方法,當getBookList方法跑出異常時將會調用getBookListFallBack方法。
    注意:回退方法應該與作為hystrix命令調用的方法具有相同的簽名。

    4.創建application.yml:

    server:
      port: 8083
    
    spring:
      application:
        name: sc-consumer-hystrix-ribbon
        
    eureka:
      client:
        registerWithEureka: false
        serviceUrl:
          defaultZone: http://localhost:8080/eureka/    

    5.測試

    依次啟動注冊中心sc-eureka、提供者sc-provider、消費者sc-consumer-hystrix-ribbon,并訪問http://localhost:8083/getBookList,結果顯示如下:

    這是提供者正常返回的值,接下來將提供者sc-provider關閉,再次訪問http://localhost:8083/getBookList,結果顯示如下:

    因為將提供者sc-provider關閉后,消費者再訪問提供者時會報錯,Hystrix捕獲異常后會直接調用回退方法也就是getBookListFallBack方法。

    在Feign上使用Hystrix

    1.在父模塊下創建子模塊項目sc-consumer-hystrix-feign,pom.xml:

    <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>
      <parent>
        <groupId>com.cf</groupId>
        <artifactId>sc-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
      </parent>
      <artifactId>sc-consumer-hystrix-feign</artifactId>
      
      <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-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
      </dependencies>
    </project>

    2.創建啟動類feign.FeignApplication:

    package feign;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    
    @SpringBootApplication
    @EnableFeignClients
    @EnableCircuitBreaker
    public class FeignApplication {
        public static void main(String[] args) {
            SpringApplication.run(FeignApplication.class, args);
        }
    }

    3.創建Feign聲明式接口:feign.inter.BookService

    package feign.inter;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.PostMapping;
    
    import feign.fallback.BookFallBack;
    
    @FeignClient(value="sc-provider", fallbackFactory=BookFallBack.class)
    public interface BookService {
        
        @GetMapping("/book/list")
        public String getBookList();
    }

    @FeignClient注解中的fallbackFactory屬性是指定的Feign客戶端界面定義回退工廠。

    4.創建調用提供者服務的Controller:

    package feign.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import feign.inter.BookService;
    
    @RequestMapping("/feign")
    @RestController
    public class FeignController {
        @Autowired
        private BookService bookService;
        
        @GetMapping("/getBookList")
        public String getBookList(){
            return bookService.getBookList();
        }
    }

    5.創建application.yml:

    server:
      port: 8084
    
    spring:
      application:
        name: sc-consumer-hystrix-feign
    
    eureka:
      client:
        registerWithEureka: false
        serviceUrl:
          defaultZone: http://localhost:8080/eureka/   
    
    feign:
      hystrix:
        enabled: true  #開啟hystrix支持     

    6.創建回退工廠類:

    package feign.fallback;
    import org.springframework.stereotype.Component;
    
    import feign.hystrix.FallbackFactory;
    import feign.inter.BookService;
    
    @Component
    public class BookFallBack implements FallbackFactory<BookService>{
        @Override
        public BookService create(Throwable cause) {
            return new BookService() {
                @Override
                public String getBookList() {
                    return "[\"Java入門到放棄\"]";
                }
            };
        }
    }

    create方法返回一個回退實例,回退實例為Feign聲明式接口BookService的實現類,提供了與BookService相對應的回退方法,BookService接口調用失敗時將會調用該實現類中的回退方法。

    7.測試:

    依次啟動注冊中心sc-eureka、提供者sc-provider、消費者sc-consumer-hystrix-feign,并訪問http://localhost:8084/feign/getBookList,結果顯示如下:

    這是提供者正常返回的值,接下來將提供者sc-provider關閉,再次訪問http://localhost:8084/feign/getBookList,結果顯示如下:

    8.查看回退原因

    修改回退工廠類BookFallBack:

    @Component
    public class BookFallBack implements FallbackFactory<BookService>{
        @Override
        public BookService create(Throwable cause) {
            return new BookService() {
                @Override
                public String getBookList() {
                    //將回退原因輸出到控制臺
                    cause.printStackTrace(System.out);
                    return "[\"Java入門到放棄\"]";
                }
            };
        }
    }

    依次啟動注冊中心sc-eureka、消費者sc-consumer-hystrix-feign,并訪問http://localhost:8084/feign/getBookList,控制臺輸出:

    com.netflix.hystrix.exception.HystrixTimeoutException
        at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1142)
        at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41)
        at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37)
        at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57)
        at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1159)
            ......

     

    版權聲明:本文為hys8298原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
    本文鏈接:https://blog.csdn.net/hys8298/article/details/101720207

    智能推薦

    [SpringCloud學習筆記4]Hystrix入門及使用

    Hystrix入門及使用 一、Hystrix簡介及功能 SpringCloud已經大大降低了我們各個服務之間的耦合性,但每個服務之間的調用卻緊密聯系,不可切斷,隨著分布式服務的數量增多,如果出現意外導致其中一個無法正常工作,會導致整個服務都停止,這顯然是不合理的. Hystrix的出現能夠在某個依賴出問題的情況下,不導致整個服務失敗.也就是說相當于一個斷路器,通過監控斷路,返回一個符合預期,可處理...

    SpringCloud-Hystrix容錯保護

    Hystrix (容錯保護) 一.分析 二.雪崩效應 在微服務架構中通常會有多個服務層調用,基礎服務的故障可能會導致級聯故障,進而造成整個系統不可用的情況,這種現象被稱為服務雪崩效應。服務雪崩效應是一種因“服務提供者”的不可用導致“服務消費者”的不可用,并將不可用逐漸放大的過程。 如果下圖所示:A作為服務提供者,B為A的服務消費者,C和D是B的服務消...

    學習springCloud(八)之Hystrix熔斷機制

    在分布式環境下,微服務之間不可避免的發生互相調用的情況,但是沒有一個系統是能保證自身絕對正確的,在服務的調用過程中,很可能面臨服務失敗的問題,因此需要一個公共組件能夠在服務通過網絡請求訪問其他微服務時,能對服務失效情況下有很強的容錯能力,對微服務提供保護和監控。 Hystrix是netflix的一個開源項目,他能夠在依賴服務失效的情況下,通過隔離系統依賴的方式,防止服務的級聯失敗(服務的雪崩) 對...

    HTML中常用操作關于:頁面跳轉,空格

    1.頁面跳轉 2.空格的代替符...

    freemarker + ItextRender 根據模板生成PDF文件

    1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...

    猜你喜歡

    電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!

    Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...

    requests實現全自動PPT模板

    http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...

    Linux C系統編程-線程互斥鎖(四)

    互斥鎖 互斥鎖也是屬于線程之間處理同步互斥方式,有上鎖/解鎖兩種狀態。 互斥鎖函數接口 1)初始化互斥鎖 pthread_mutex_init() man 3 pthread_mutex_init (找不到的情況下首先 sudo apt-get install glibc-doc sudo apt-get install manpages-posix-dev) 動態初始化 int pthread_...

    統計學習方法 - 樸素貝葉斯

    引入問題:一機器在良好狀態生產合格產品幾率是 90%,在故障狀態生產合格產品幾率是 30%,機器良好的概率是 75%。若一日第一件產品是合格品,那么此日機器良好的概率是多少。 貝葉斯模型 生成模型與判別模型 判別模型,即要判斷這個東西到底是哪一類,也就是要求y,那就用給定的x去預測。 生成模型,是要生成一個模型,那就是誰根據什么生成了模型,誰就是類別y,根據的內容就是x 以上述例子,判斷一個生產出...

    精品国产乱码久久久久久蜜桃不卡