javascript
Spring Cloud Alibaba迁移指南2:一行代码从Hystrix迁移到Sentinel
作者:洛夜,校對:周立
在本博客首發,歡迎轉載。
前段時間,Netflix宣布Hystrix進入維護模式,詳見Hystrix停止開發,我們該何去何從?,而Spring Cloud亦宣布Spring Cloud Netflix進入維護狀態,后續不再進行更新已成為事實。作為開發者的我們,如何使用極簡的方式替換Hystrix成為首要解決的問題。
Hystrix宣布停止維護后,社區推薦了Resilience4j( https://github.com/resilience4j/resilience4j ) ,而業界還有Alibaba Sentinel可供選擇——3款產品各有優勢,具體的功能差異參考下表(該表來自Sentinel Wiki( https://github.com/alibaba/Sentinel/wiki/Guideline:-%E4%BB%8E-Hystrix-%E8%BF%81%E7%A7%BB%E5%88%B0-Sentinel#%E5%8A%9F%E8%83%BD%E5%AF%B9%E6%AF%94 ):
| 隔離策略 | 信號量隔離(并發線程數限流) | 線程池隔離/信號量隔離 | 信號量隔離 |
| 熔斷降級策略 | 基于響應時間、異常比率、異常數 | 基于異常比率 | 基于異常比率、響應時間 |
| 實時統計實現 | 滑動窗口(LeapArray) | 滑動窗口(基于 RxJava) | Ring Bit Buffer |
| 動態規則配置 | 支持多種數據源 | 支持多種數據源 | 有限支持 |
| 擴展性 | 多個擴展點 | 插件的形式 | 接口的形式 |
| 基于注解的支持 | 支持 | 支持 | 支持 |
| 限流 | 基于 QPS,支持基于調用關系的限流 | 有限的支持 | Rate Limiter |
| 流量整形 | 支持預熱模式、勻速器模式、預熱排隊模式 | 不支持 | 簡單的 Rate Limiter 模式 |
| 系統自適應保護 | 支持 | 不支持 | 不支持 |
| 控制臺 | 提供開箱即用的控制臺,可配置規則、查看秒級監控、機器發現等 | 簡單的監控查看 | 不提供控制臺,可對接其它監控系統 |
目前,Sentinel 在?Spring Cloud Alibaba中已適配Spring Cloud體系,完全可用來替代 Hystrix 的功能。不僅如此,阿里內部很多產品線都已使用Sentinel實現限流降級,Sentinel是經過生產流量大規模驗證的。
下面來探討如何從Hystrix遷移至Sentinel——
Spring Cloud Alibaba Sentinel 代替 Hystrix
要想使用Spring Cloud Alibaba Sentinel,需添加如下依賴,并去除Spring Cloud Netflix Hystrix(?spring-cloud-starter-netflix-hystrix?)的依賴。
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-alibaba-sentinel</artifactId><version>0.2.1.RELEASE</version> </dependency>0代碼修改兼容 Feign
加上 Feign 的依賴:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId><version>${latest.version}</version> </dependency>在?application.yml?中添加?feign.sentinel.enabled=true?即可為Feign啟用Sentinel支持:
# 去掉 # feign.hystrix.enabled: true # 改為如下即可 feign.sentinel.enabled: trueFeign Client無需修改:
@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。
只需配置這些規則,限流降級操作即可生效。
一行代碼支持RestTemplate
Sentinel與Spring生態的?RestTemplate?也進行了整合,可對?RestTemplate?請求過程進行限流和降級,只需在構造 RestTemplate 的時候加上?@SentinelRestTemplate?注解即可,如下所示:
@Bean @SentinelRestTemplate public RestTemplate restTemplate() {return new RestTemplate(); }@SentinelRestTemplate?注解還暴露出了對應的屬性可進行限流降級后的自定義錯誤,默認的行為是返回 "RestTemplate request block by sentinel" 信息。關于?@SentinelRestTemplate?的詳細信息可參考Wiki( https://github.com/spring-cloud-incubator/spring-cloud-alibaba/wiki/Sentinel#resttemplate-%E6%94%AF%E6%8C%81 )。
總結
以上是生活随笔為你收集整理的Spring Cloud Alibaba迁移指南2:一行代码从Hystrix迁移到Sentinel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有赞多级缓存解决方案怎么做的,你知道吗?
- 下一篇: 春招收获阿里腾讯实习offer,学习、面