摘要: 本文對Hystrix、Resilience4j、Sentinel進行對比,並探討如何使用一行代碼這種極簡的方式,將Hystrix遷移到Sentinel。 Hystrix 自從前段時間 宣佈中止維護以後,社區推薦了 resilience4j。git
自 Spring Cloud 官方宣佈 Spring Cloud Netflix 進入維護狀態後,咱們開始製做《Spring Cloud Alibaba遷移指南》系列文章,向開發者提供更多的技術選型方案,並下降遷移過程當中的技術難度。github
第一篇,咱們對Hystrix、Resilience4j 和 Sentinel 三個開源項目進行對比,並探討如何使用一行代碼這種極簡的方式,將Hystrix遷移到Sentinel。spring
Hystrix 自從前段時間 宣佈中止維護以後,社區推薦了 resilience4j。這 3 款產品各有優劣勢,具體的功能差別參考下表(該表來源 Sentinel Wiki):編程
Sentinel | Hystrix | resilience4j | |
---|---|---|---|
隔離策略 | 信號量隔離(併發線程數限流) | 線程池隔離/信號量隔離 | 信號量隔離 |
熔斷降級策略 | 基於響應時間、異常比率、異常數 | 基於異常比率 | 基於異常比率、響應時間 |
實時統計實現 | 滑動窗口(LeapArray) | 滑動窗口(基於 RxJava) | Ring Bit Buffer |
動態規則配置 | 支持多種數據源 | 支持多種數據源 | 有限支持 |
擴展性 | 多個擴展點 | 插件的形式 | 接口的形式 |
基於註解的支持 | 支持 | 支持 | 支持 |
限流 | 基於 QPS,支持基於調用關係的限流 | 有限的支持 | Rate Limiter |
流量整形 | 支持預熱模式、勻速器模式、預熱排隊模式 | 不支持 | 簡單的 Rate Limiter 模式 |
系統自適應保護 | 支持 | 不支持 | 不支持 |
控制檯 | 提供開箱即用的控制檯,可配置規則、查看秒級監控、機器發現等 | 簡單的監控查看 | 不提供控制檯,可對接其它監控系統 |
目前 Sentinel 在 Spring Cloud Alibaba 項目中已經適配了 Spring Cloud 體系,能夠用來徹底替代 Hystrix 的功能了。微信
Spring Cloud Alibaba Sentinel 主要是爲了整合 Sentinel 和 Spring Boot/Cloud 技術棧。目前完成了以下功能:併發
想要使用 Spring Cloud Alibaba Sentinel,須要加上依賴信息:app
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel</artifactId> <version>0.2.1.RELEASE</version> </dependency>
加上 Feign 的依賴:ide
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>${latest.version}</version> </dependency>
把 hystrix 的配置改爲 sentinel 的便可使用 Sentinel 的限流降級功能:ui
# feign.hystrix.enabled: true feign.sentinel.enabled: true
@FeignClient(name = "service-provider") public interface EchoService { @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) String echo(@PathVariable("str") String str); @RequestMapping(value = "/echo/save", method = RequestMethod.POST) String save(Foo foo); }
對於這個 EchoService
,echo 方法對應的資源名是 GET:http://service-provider/echo/{str}
, save 方法對應的資源名是 POST:http://service-provider/echo/save
。阿里雲
只需配置這些規則,限流降級操做便可當即生效。
Sentinel 還跟 Spring 生態的 RestTemplate
作了整合,能夠對 RestTemplate
請求過程進行限流和降級操做,只須要在構造 RestTemplate 的時候加上 @SentinelRestTemplate
註解便可:
@Bean @SentinelRestTemplate public RestTemplate restTemplate() { return new RestTemplate(); }
@SentinelRestTemplate
註解還暴露出了對應的屬性可進行限流降級後的自定義錯誤,默認的行爲是返回 "RestTemplate request block by sentinel" 信息。關於 @SentinelRestTemplate
的詳細信息能夠參考 Wiki。
原文連接 更多技術乾貨 請關注阿里云云棲社區微信號 :yunqiinsight