- springColud目錄
Hystrix簡介
- Hystrix 能使你的系統在出現依賴服務失效的時候,通過隔離系統所依賴的服務,防止服務級聯失敗,同時提供失敗回退機制,更優雅地應對失效,并使你的系統能更快地從異常中恢複。
Hystrix能做什麼
- 在通過第三方用戶端通路(通常是通過網絡)依賴服務出現高延遲或者失敗時,為系統提供保護和控制
- 在分布式系統中防止級聯失敗
- 快速失敗(Fail fast)同時能快速恢複
- 提供失敗回退(Fallback)和優雅的服務降級機制
- 提供近實時的監控、報警和運維控制手段
Hystrix 設計原則
- 防止單個依賴耗盡容器(例如 Tomcat)内所有使用者線程
- 降低系統負載,對無法及時處理的請求快速失敗(fail fast)而不是排隊
- 提供失敗回退,以在必要時讓失效對使用者透明化
- 使用隔離機制(例如『艙壁』/『泳道』模式,熔斷器模式等)降低依賴服務對整個系統的影響
- 針對系統服務的度量、監控和報警,提供優化以滿足近實時性的要求
- 在 Hystrix 絕大部分需要動态調整配置并快速部署到所有應用方面,提供優化以滿足快速恢複的要求
- 能保護應用不受依賴服務的整個執行過程中失敗的影響,而不僅僅是網絡請求
Hystrix 使用
1.配置依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2.入口程式上增加@EnableCircuitBreaker注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
public class MicroserviceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerApplication.class, args);
}
}
3.配置檔案配置hystrix預設逾時時間,預設即為5000,如無特殊需求不要更改
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
基于Fegin的熔斷
1.首先開啟對全局Hystrix的支援,舊版中預設是開啟,現在的版本則是預設false
- feign.hystrix.enabled = true
2.為feignClient添加fallback
@FeignClient(name = "microservice-provider", fallback = HystrixClientFallback.class)
public interface UserFeignClient {
@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id);
}
3.fallback 類要繼承feignClient接口,并實作方法。如果feign通路其它微服務失敗,則調用fallback 對應的方法傳回預設值。
public class HystrixClientFallback implements UserFeignClient {
@Override
public User findById(Long id) {
User user = new User();
user.setId(0L);
return user;
}
}
controller 中實作熔斷
- @HystrixCommand 指定融斷方法 注意熔斷器的方法一定和原方法的名稱保持一緻
- 下面的isolation表示findByFeginId與 findByIdFallback 在同一線程。不配置表示預設兩個方法在不同的線程,其中findByIdFallback在隔離線程。
- findByFeginId方法如果通路失敗,則調用fallbackMethod 方法取值
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
private UserFeignClient userFeignClient;
@HystrixCommand(fallbackMethod = "findByIdFallback",commandProperties = @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"))
@GetMapping("/movief/{id}")
public User findByFeginId(@PathVariable Long id) {
return userFeignClient.findById(id);
}
public User findByIdFallback(Long id) {
User user = new User();
user.setId(6L);
return user;
}
Feign 采用FallbackFactory 實作熔斷
1.feignClient
@FeignClient(name = "microservice-provider", fallbackFactory = HystrixClientFactory.class)
public interface UserFeignClient {
@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id); // 兩個坑:1. @GetMapping不支援 2. @PathVariable得設定value
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User postUser(@RequestBody User user);
}
2.fallbackFactory實作
- 使用fallbackFactory的好處是可以添加自定義的日志
- create傳回的是實作feignClient接口的對象執行個體,這裡簡單借用一下上面基于Fegin的熔斷的HystrixClientFallback方法
@Component
public class HystrixClientFactory implements FallbackFactory<UserFeignClient> {
private static final Logger LOGGER = LoggerFactory.getLogger(HystrixClientFactory.class);
@Override
public UserFeignClient create(Throwable throwable) {
HystrixClientFactory.LOGGER.info("fallback; reason was: {}", throwable.getMessage());
return new HystrixClientFallback();
}
}
局部關閉Hystrix支援
- Feign 預設支援Hystrix。Feign.Builder: HystrixFeign.Builder
- 關閉Hystrix的支援隻需要修改feignClient的配置檔案中的feignBuilder配置,如下:
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
檢視Hystrix狀态
http://localhost:8032/hystrix.stream 檢視Hystrix資訊 http://localhost:8032/health 檢視監控狀态
使用Hystrix DashBoard檢視Hystrix資訊
- 由于Hystrix傳回的資訊是文本資料,不容易直覺檢視,需要進行整理分析。DashBoard就是對Hystrix資訊的圖形展現工具。
1.建立一個springboot項目
2.添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
3.入口程式上增加@EnableHystrixDashboard注解
@EnableHystrixDashboard
@SpringBootApplication
public class HystrixDashBoardApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixDashBoardApplication.class, args);
}
}
4.配置端口
server.port= 8060
- 通路位址 http://localhost:8060/hystrix
- 填寫要檢測的hystrix: http://localhost:8032/hystrix.stream,展現如下