系統容錯工具html
降級java
熔斷git
// 當調用遠程服務失敗,跳轉到指定的方法,執行降級代碼 @HystrixCommand(fallbackMethod="方法名") 遠程調用方法() { restTemplate.getForObject(url,......); }
說明:這是沒有hystrix的狀況,下來測試hystrix提供的降級處理方式github
`<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>`
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); } }
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.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 對請求的降級和熔斷,能夠產生監控信息,hystrix dashboard能夠實時的進行監控shell
springboot 提供的日誌監控工具,能夠暴露項目中多種監控信息apache
添加 actuatorwindows
yml 配置暴露監控數據緩存
actuator 是 spring boot 提供的服務監控工具,提供了各類監控信息的監控端點management.endpoints.web.exposure.include
配置選項,
能夠指定端點名,來暴露監控端點
若是要暴露全部端點,能夠用 「*」
右鍵點擊項目或pom.xml, 編輯起步依賴, 添加 actuator 依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
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: "*"
儀表盤項目能夠是一個徹底獨立的項目,與其餘項目都無關,也不用向註冊表註冊
hystrix: dashboard: proxy-stream-allow-list: localhost
<?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>
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); } }
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/
短路器打開的條件:
短路器打開後,全部請求直接執行降級代碼 斷路器打開幾秒後,會進入**半開狀態**,客戶端調用會嘗試向後臺服務發送一次調用, 若是調用成功,斷路器能夠自動關閉,恢復正常 若是調用仍然失敗,繼續保持打開狀態幾秒鐘
整個鏈路達到必定的閾值,默認狀況下,10秒內產生超過20次請求,則符合第一個條件。
知足第一個條件的狀況下,若是請求的錯誤百分比大於閾值,則會打開斷路器,默認爲50%。
Hystrix的邏輯,先判斷是否知足第一個條件,再判斷第二個條件,若是兩個條件都知足,則會開啓斷路器
斷路器打開 5 秒後,會處於半開狀態,會嘗試轉發請求,若是仍然失敗,保持打開狀態,若是成功,則關閉斷路器
http://httpd.apache.org/docs/current/platform/windows.html#down
ab -n 20000 -c 50 http://localhost:3001/item-service/35
https://github.com/Netflix/Hystrix/wiki/Configuration
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix.command.default.circuitBreaker.requestVolumeThreshold
hystrix.command.default.circuitBreaker.errorThresholdPercentage
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds
斷路器打開多長時間後,再次容許嘗試訪問(半開),仍失敗則繼續保持打開狀態,如成功訪問則關閉斷路器,默認 5000