<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Hystrix 斷路器模式 – SpringCloud > 原文:[https://howtodoinjava.com/spring-cloud/spring-hystrix-circuit-breaker-tutorial/](https://howtodoinjava.com/spring-cloud/spring-hystrix-circuit-breaker-tutorial/) 了解如何利用稱為 [Hystrix](https://github.com/Netflix/Hystrix) 的 [Spring cloud Netflix](https://howtodoinjava.com/spring/spring-cloud/spring-cloud-service-discovery-netflix-eureka/) 堆棧組件之一來實現**斷路器**,同時調用基礎[微服務](https://howtodoinjava.com/microservices/microservices-definition-principles-benefits/)。 通常需要在某些基礎服務永久關閉/拋出錯誤的應用程序中啟用容錯功能,我們需要自動退回到程序執行的不同路徑。 這與使用大量底層微服務的生態系統的分布式計算風格有關。 這是斷路器模式的幫助之處,Hystrix 是構建此斷路器的工具。 ## Hystrix 示例 Hystrix 配置通過四個主要步驟完成。 1. 添加 Hystrix 啟動器和儀表板依賴項。 ```java <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId> </dependency> ``` 2. 添加`@EnableCircuitBreaker`注解 3. 添加`@EnableHystrixDashboard`注解 4. 添加注解`@HystrixCommand(fallbackMethod = "myFallbackMethod")` ## 什么是斷路器模式? 如果我們在基于微服務的體系結構上設計系統,則通常會開發許多微服務,并且這些微服務會在實現某些業務目標時相互影響很大。 現在,我們所有人都可以假設,如果所有服務都已啟動并且正在運行,并且每個服務的響應時間令人滿意,那么這將給出預期的結果。 現在,如果當前生態系統的任何服務出現問題并停止為請求提供服務,將會發生什么。 這將導致超時/異常,并且由于此單點故障,整個生態系統將變得不穩定。 在這里,斷路器模式非常方便,一旦發現任何此類情況,它將流量重定向到回退路徑。 它還會密切監視有缺陷的服務,并在服務恢復正常后恢復流量。 因此,斷路器是進行服務調用的方法的一種包裝,它監視服務的運行狀況,一旦出現問題,斷路器將跳閘,所有進一步的調用都將返回到斷路器,最后一旦服務回來了就自動恢復! 太酷了吧? ![](https://img.kancloud.cn/a7/ab/a7abe0ad6ea838920ff29cf43d041533_391x460.jpg) 斷路器調用順序 ## Hystrix 斷路器示例 為了演示斷路器,我們將創建以下兩個微服務,其中第一個微服務依賴于另一個。 * **學生微服務** – 將提供`Student`實體的一些基本功能。 這將是一個基于 REST 的服務。 我們將從`School`服務中調用此服務,以了解斷路器。 它將在本地主機的端口`8098`上運行。 * **學校微服務** – 同樣是一個簡單的基于 REST 的微服務,我們將使用 Hystrix 實現斷路器。 `Student`服務將從此處調用,一旦學生服務不可用,我們將測試后備路徑。 它將在本地主機的端口 9098 上運行。 #### 技術棧和演示運行時 * Java 1.8 * Eclipse 作為 IDE * Maven 作為構建工具 * Spring Cloud Hystrix 作為斷路器框架 * SpringBoot * SpringRest ## 創建學生服務 請按照以下步驟創建和運行學生服務-一個簡單的 REST 服務,提供學生實體的一些基本功能。 #### 創建 spring boot 項目 從[ Spring Boot 初始化器頁面](https://start.spring.io/)創建具有三個依賴項的 Spring Boot 項目,即`Web`,`Rest Repositories`和`Actuator`。 給出其他 Maven GAV 坐標并下載項目。 ![](https://img.kancloud.cn/83/02/83028d8bc21a1d6e6802b60ea3b71259_1353x697.jpg) 學生服務生成 將項目解壓縮并將其作為現有的 maven 項目導入 Eclipse。 在此步驟中,將從 maven 存儲庫下載所有必需的依賴項。 #### 服務器端口設置 打開`application.properties`并添加端口信息。 ```java server.port = 8098 ``` 這將使該應用程序在默認端口 8098 上運行。通過在啟動服務器時提供 `-Dserver.port = XXXX`參數,可以輕松地覆蓋此應用程序。 #### 創建 REST API 現在添加一個稱為`StudentServiceController`的 REST 控制器類,并公開一個其余端點,以獲取特定學校的所有學生詳細信息。 在這里,我們公開`/getStudentDetailsForSchool/{schoolname}`端點來滿足業務目的。 為簡單起見,我們正在對學生詳細信息進行硬編碼。 `StudentServiceController.java` ```java package com.example.howtodoinjava.springhystrixstudentservice.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.example.howtodoinjava.springhystrixstudentservice.domain.Student; @RestController public class StudentServiceController { private static Map<String, List<Student>> schooDB = new HashMap<String, List<Student>>(); static { schooDB = new HashMap<String, List<Student>>(); List<Student> lst = new ArrayList<Student>(); Student std = new Student("Sajal", "Class IV"); lst.add(std); std = new Student("Lokesh", "Class V"); lst.add(std); schooDB.put("abcschool", lst); lst = new ArrayList<Student>(); std = new Student("Kajal", "Class III"); lst.add(std); std = new Student("Sukesh", "Class VI"); lst.add(std); schooDB.put("xyzschool", lst); } @RequestMapping(value = "/getStudentDetailsForSchool/{schoolname}", method = RequestMethod.GET) public List<Student> getStudents(@PathVariable String schoolname) { System.out.println("Getting Student details for " + schoolname); List<Student> studentList = schooDB.get(schoolname); if (studentList == null) { studentList = new ArrayList<Student>(); Student std = new Student("Not Found", "N/A"); studentList.add(std); } return studentList; } } ``` `Student.java` ```java package com.example.howtodoinjava.springhystrixstudentservice.domain; public class Student { private String name; private String className; public Student(String name, String className) { super(); this.name = name; this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } } ``` #### 建立并測試學生服務 現在,使用`mvn clean install`進行最終構建,并使用命令`java -jar target\spring-hystrix-student-service-0.0.1-SNAPSHOT.jar`運行服務器。 這將在默認端口`8098`中啟動學生服務。 打開瀏覽器,然后輸入`http://localhost:8098/getStudentDetailsForSchool/abcschool`。 它應在瀏覽器中顯示以下輸出: ![](https://img.kancloud.cn/0f/0d/0f0deb571171c5ef01f11ace4cf519b9_596x280.jpg) 學生服務響應 ## 創建學校服務 - 啟用 Hystrix 與學生服務類似,為學校創建另一個微服務。 它將在內部調用已開發的學生服務。 #### 生成 Spring Boot 項目 從[ Spring Boot 初始化器頁面](https://start.spring.io/)主要使用那些依賴項創建一個 Spring Boot 項目。 * **Web** – REST 端點 * **執行器** – 提供基本管理 URL * **Hystrix** – 啟用斷路器 * **Hystrix 儀表板** – 啟用一個與斷路器監控相關的儀表板屏幕 給出其他 Maven GAV 坐標并下載項目。 ![](https://img.kancloud.cn/53/6c/536cc2ad7a245c09f740de708ca3eba7_1350x700.jpg) 學校服務項目 將項目解壓縮并作為現有 maven 項目導入到 Eclipse 中。 在此步驟中,將從 maven 存儲庫下載所有必需的依賴項。 #### 服務器端口設置 打開`application.properties`并添加端口信息。 ```java server.port = 9098 ``` 這將使該應用程序在默認端口 9098 上運行。通過在啟動服務器時提供 `-Dserver.port = XXXX`參數,可以輕松地覆蓋此應用程序。 #### 啟用 Hystrix 設置 打開`SpringHystrixSchoolServiceApplication`,即使用`@SpringBootApplication`生成的類,并添加`@EnableHystrixDashboard`和`@EnableCircuitBreaker`注解。 這將**在應用程序中啟用 Hystrix 斷路器**,還將添加一個在 Hystrix 提供的`localhost`上運行的有用儀表板。 ```java package com.example.howtodoinjava.springhystrixschoolservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; @SpringBootApplication @EnableHystrixDashboard @EnableCircuitBreaker public class SpringHystrixSchoolServiceApplication { public static void main(String[] args) { SpringApplication.run(SpringHystrixSchoolServiceApplication.class, args); } } ``` #### 添加 REST 控制器 在我們將公開`/getSchoolDetails/{schoolname}`端點的位置添加`SchoolServiceController` Rest 控制器,該端點將僅返回學校詳細信息及其學生詳細信息。 對于學生詳細信息,它將調用已經開發的學生服務端點。 我們將創建一個代表層`StudentServiceDelegate.java`來調用學生服務。 這個簡單的代碼看起來像 `SchoolServiceController.java` ```java package com.example.howtodoinjava.springhystrixschoolservice.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.example.howtodoinjava.springhystrixschoolservice.delegate.StudentServiceDelegate; @RestController public class SchoolServiceController { @Autowired StudentServiceDelegate studentServiceDelegate; @RequestMapping(value = "/getSchoolDetails/{schoolname}", method = RequestMethod.GET) public String getStudents(@PathVariable String schoolname) { System.out.println("Going to call student service to get data!"); return studentServiceDelegate.callStudentServiceAndGetData(schoolname); } } ``` **StudentServiceDelegate** 我們將在此處執行以下操作以啟用 Hystrix 斷路器。 * 通過提供的 Spring 框架調用學生服務`RestTemplate` * 添加 Hystrix 命令以啟用回退方法 – `@HystrixCommand(fallbackMethod = "callStudentServiceAndGetData_Fallback")` – 這意味著我們將不得不添加另一個具有相同簽名的方法`callStudentServiceAndGetData_Fallback`,當實際的學生服務關閉時將調用該方法。 * 添加后備方法 – `callStudentServiceAndGetData_Fallback`,它將僅返回一些默認值。 ```java package com.example.howtodoinjava.springhystrixschoolservice.delegate; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; @Service public class StudentServiceDelegate { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "callStudentServiceAndGetData_Fallback") public String callStudentServiceAndGetData(String schoolname) { System.out.println("Getting School details for " + schoolname); String response = restTemplate .exchange("http://localhost:8098/getStudentDetailsForSchool/{schoolname}" , HttpMethod.GET , null , new ParameterizedTypeReference<String>() { }, schoolname).getBody(); System.out.println("Response Received as " + response + " - " + new Date()); return "NORMAL FLOW !!! - School Name - " + schoolname + " ::: " + " Student Details " + response + " - " + new Date(); } @SuppressWarnings("unused") private String callStudentServiceAndGetData_Fallback(String schoolname) { System.out.println("Student Service is down!!! fallback route enabled..."); return "CIRCUIT BREAKER ENABLED!!! No Response From Student Service at this moment. " + " Service will be back shortly - " + new Date(); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ``` #### 建立和測試學校服務 現在,使用`mvn clean install`進行最終構建,并使用命令`java -jar target\spring-hystrix-school-service-0.0.1-SNAPSHOT.jar`運行服務器。 這將在默認端口 **9098** 中啟動學校服務。 如上所述啟動學生服務,然后通過打開瀏覽器并鍵入`http://localhost:9098/getSchoolDetails/abcschool`來測試學校服務。 它應該在瀏覽器中顯示以下輸出: ![](https://img.kancloud.cn/3f/16/3f16a4e35ca29cc65c842fc3ec5c9905_1276x168.jpg) 學校服務響應 ## 測試 Hystrix 斷路器 - 演示 打開瀏覽器,然后輸入`http://localhost:9098/getSchoolDetails/abcschool`。 它應在瀏覽器中顯示以下輸出: ![](https://img.kancloud.cn/3f/16/3f16a4e35ca29cc65c842fc3ec5c9905_1276x168.jpg) 學校服務響應 現在我們已經知道,學校服務在內部調用學生服務,并且正在從該服務獲取學生詳細信息。 因此,如果兩個服務都在運行,則學校服務將顯示學生服務返回的數據,正如我們在上面的學校服務瀏覽器輸出中所看到的那樣。 這是**電路關閉狀態**。 現在,讓我們停止學生服務,只需在學生服務服務器控制臺中按`CTRL + C`(停止服務器),然后從瀏覽器再次測試學校服務。 這次它將返回回退方法響應。 Hystrix 出現在這里,它會頻繁地監視學生服務,并且在停機時,Hystrix 組件已打開電路并啟用了后備路徑。 這是瀏覽器中的回退輸出。 ![](https://img.kancloud.cn/0e/81/0e810b565cc1f2183b0de10f18512f45_1166x148.jpg) 學校服務響應回退路徑 再次啟動學生服務,等待片刻,然后返回學校服務,它將再次開始以正常流程進行響應。 ## Hystrix 儀表板 當我們添加了 hystrix 儀表板依賴時,hystrix 在以下 URL 中提供了一個不錯的儀表盤和 Hystrix 流: * **`http://localhost:9098/hystrix.stream`** – Hystrix 產生的連續流。 這只是健康檢查結果以及 Hystrix 正在監視的所有服務呼叫。 示例輸出在瀏覽器中將如下所示: ![](https://img.kancloud.cn/c3/a6/c3a699ff24b392960a62c66090f01329_1337x696.jpg) Hystrix 流式輸出 * **`http://localhost:9098/hystrix`** – 這是可視儀表板的初始狀態。 ![](https://img.kancloud.cn/d7/4f/d74f70fa3745e6879315dde5ce14cf39_1282x628.jpg) Hystrix 初始儀表盤 * 現在,在儀表板中添加`http://localhost:9098/hystrix.stream`,以獲得由 Hystrix 組件監視的電路的有意義的動態視覺表示。 在主頁中提供流式輸入后的虛擬儀表盤: ![](https://img.kancloud.cn/79/d1/79d1532a6d07f478dcb8b459958bca7e_1361x468.jpg) Hystrix 虛擬儀表盤 ## 總結 這就是**可以制造 Spring 開關 Hystrix 斷路器**的全部內容,我們已經測試了**電路開放路徑**和**電路閉合路徑**。 自行進行設置,并使用不同的組合服務狀態以更清楚地了解整個概念。 如果您在執行本文時遇到任何困難,請添加評論。 我們將很樂意調查這個問題。 [下載源碼](https://howtodoinjava.com/wp-content/uploads/2017/07/Circuit-Breaker.zip) 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看