1. Hystrix 斷路器 概念
Hystrix是一個用於分佈式系統的延遲和容錯的開源庫,在分佈式系統中,許多依賴會不可避免的調用失敗,例如超時,異常等,Hystrix能保證在一個依賴出現問題的情況下,不會導致整體服務失敗,避免級聯故障,以提高分佈式系統的彈性。
- 爲系統提供保護和控制
- 以進行快速失敗,縮短延遲等待時間
- 提供失敗回退(Fallback)和相對優雅的服務降級機制
- 提供有效的服務容錯監控、報警和運維控制手段
1.1 配置依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
1.2 application.yml 配置
feign:
hystrix:
enabled: true #開啓feign的熔斷機制
1.3 啓動類配置
只需要在啓動類上加上@EnableCircuitBreaker註解即可,如下所示:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class ShopConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ShopConsumerApplication.class, args);
}
}
1.4 接口的編寫
使用@FeignClient註解 name=“服務名” fallback=“降級服務調用接口”
例如: Service層中如果調取失敗就走指定的降級類
@Service
@FeignClient(name = "ms-provider", fallback = TestServiceFellback.class)
public interface TicketService {
@RequestMapping("/test/test01")
public Object getAllTicket();
}
實現一個降級服務後的快速響應
@Component
public class TestServiceFellback implements TicketService {
@Override
public Object getAllTicket() {
return "熔斷入口";
}
}
最終實現跳閘後的接口
2. Hystrix 監控
2.1 配置依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
2.2 啓動類配置
在啓動類上加上@EnableHystrixDashboard註解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrixDashboard
public class ShopConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ShopConsumerApplication.class, args);
}
}
2.3 接口的編寫(需要提供降級後走的服務)
編寫一個config
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/actuator/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
2.4 訪問Hystrix Dashboard
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-nkRDqJyU-1570769816291)(467377DCD5FF4F60B14AA714576CBF24)]
在輸入框中輸入:http://locahost:8080 + 設定的地址 我的是 /actuator/hystrix.stream
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-jwVKcQQV-1570769816293)(00A7C653C73D4C758BAE84860402D229)]
2.5 Hystrix 超時設置
如果有需求需要設置時間就在application.yml中配置
hystrix:
command:
default: #default全局有效,service id指定應用有效
execution:
timeout:
#如果enabled設置爲false,則請求超時交給ribbon控制,爲true,則超時作爲熔斷根據
enabled: true
isolation:
thread:
timeoutInMilliseconds: 50000 #斷路器超時時間,默認1000ms