Hystrix:斷路器,容錯管理工具,旨在經過熔斷機制控制服務和第三方庫的節點,從而對延遲和故障提供更強大的容錯能力。java
hystrix能夠實現降級和熔斷:web
降級spring
熔斷apache
在微服務系統中,服務之間進行依賴,避免有調用其中服務失敗,而引發其餘服務大範圍宕機,形成雪崩效應,hystrix熔斷可在知足熔斷條件(默認10秒20次以上請求,同時50%失敗)後執行降級。快速斷開故障服務,保護其餘服務不受影響。springboot
第一步:sp06添加hystrix依賴服務器
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
第二步:主程序添加 @EnableCircuitBreaker 啓用 hystrix 斷路器併發
package cn.tedu.sp06; 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.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @EnableCircuitBreaker @SpringBootApplication public class Sp06RibbonApplication { public static void main(String[] args) { SpringApplication.run(Sp06RibbonApplication.class, args); } /** * 建立RestTemplate實例 * 放入spring容器 * @LoadBalanced-對RestTemplate進行加強,封裝RestTemplate,添加負載均衡功能 */ @LoadBalanced @Bean public RestTemplate restTemplate(){ //設置調用超時時間,超時後認爲調用失敗 SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory(); f.setConnectTimeout(1000);//創建鏈接等待時間 f.setReadTimeout(1000);//鏈接創建後,發送請求後,等待接收響應的時間 return new RestTemplate(f); } }
第三步:RibbonController 中添加降級方法app
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 rt; @GetMapping("/item-service/{orderId}") @HystrixCommand(fallbackMethod = "getItemsFB") //指定降級方法的方法名 public JsonResult<List<Item>> getItems(@PathVariable String orderId){ return rt.getForObject("http://item-service/{1}", JsonResult.class,orderId); } @PostMapping("/item-service/decreaseNumber") @HystrixCommand(fallbackMethod = "decreaseNumberFB") //指定降級方法的方法名 public JsonResult<?> decreaseNumber(@PathVariable List<Item> items){ return rt.postForObject("http://item-service/decreaseNumber",items, JsonResult.class); } @GetMapping("/user-service/{userId}") @HystrixCommand(fallbackMethod = "getUserFB") //指定降級方法的方法名 public JsonResult<User> getUser(@PathVariable Integer userId) { return rt.getForObject("http://user-service/{1}", JsonResult.class, userId); } @GetMapping("/user-service/{userId}/score") @HystrixCommand(fallbackMethod = "addScoreFB") //指定降級方法的方法名 public JsonResult addScore( @PathVariable Integer userId, Integer score) { return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score); } @GetMapping("/order-service/{orderId}") @HystrixCommand(fallbackMethod = "getOrderFB") //指定降級方法的方法名 public JsonResult<Order> getOrder(@PathVariable String orderId) { return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId); } @GetMapping("/order-service") @HystrixCommand(fallbackMethod = "addOrderFB") //指定降級方法的方法名 public JsonResult addOrder() { return rt.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("添加訂單失敗"); } }
第四步:啓動eureka、item和hystrix服務器進行測試
http://localhost:3001/item-service/35負載均衡
hystrix超時設置:
超時時間設置應該超過ribbon重試時間,不然重試失效。spring-boot
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix等待超時後, 會執行降級代碼, 快速向客戶端返回降級結果, 默認超時時間是1000毫秒。
可在yml中設置超時時間:
hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 6000
主程序添加 @EnableCircuitBreaker 啓用 hystrix 斷路器,熔斷自動打開。
Hystrix使用springboot提供的actuator健康管理,監控各個端點。
actuator中的hystrix.stream能夠監控hystrix斷路器各端點日誌。
第一步:sp06的pom中添加actuator依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>2.4.0</version> </dependency>
第二步:在yml中配置健康監控的內容
# "*"暴露全部監控端點 management: endpoints: web: exposure: include: "*"
第三步:測試actuator健康監控
http://localhost:3001/actuator/
搭建Hystrix Dashboard儀表盤:
儀表盤項目是一個徹底獨立的項目。
第一步:建立springboot項目sp08-htstrix-dashboard
第二步:添加hystrix dashboard依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId> </dependency>
第三步:主程序上添加@EnableHystrixDashboard註解
package cn.tedu.sp08; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; @EnableHystrixDashboard @SpringBootApplication public class Sp08HystrixDashboardApplication { public static void main(String[] args) { SpringApplication.run(Sp08HystrixDashboardApplication.class, args); } }
第四步:配置容許給那些服務器開啓權限
hystrix: dashboard: proxy-stream-allow-list: localhost
第五步:監控查看
http://localhost:4001/hystrix/
第六步:查看hystrix stream監控數據端點
輸入hystrix監控地址
訪問item/user/order服務器,查看儀表盤。
第六步:使用ab進行併發訪問測試
使用 apache 的併發訪問測試工具 ab進行訪問測試。
打開ab工具/bin文件目錄--cmd--輸入命令:
ab -n 20000 -c 50 http://localhost:3001/item-service/35
併發50,發送20000個請求,查看儀表盤。