Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
自 Spring Cloud 官方宣布 Spring Cloud Netflix 進入維護狀態后,我們開始制作《Spring Cloud Alibaba遷移指南》系列文章,向開發者提供更多的技術選型方案,并降低遷移過程中的技術難度。
第一篇,我們對Hystrix、Resilience4j 和 Sentinel 三個開源項目進行對比,并探討如何使用一行代碼這種極簡的方式,將Hystrix遷移到Sentinel。
Hystrix 自從前段時間?宣布停止維護之后,社區推薦了?resilience4j。這 3 款產品各有優劣勢,具體的功能差異參考下表(該表來源?Sentinel Wiki):
| 隔離策略 | 信號量隔離(并發線程數限流) | 線程池隔離/信號量隔離 | 信號量隔離 |
| 熔斷降級策略 | 基于響應時間、異常比率、異常數 | 基于異常比率 | 基于異常比率、響應時間 |
| 實時統計實現 | 滑動窗口(LeapArray) | 滑動窗口(基于 RxJava) | Ring Bit Buffer |
| 動態規則配置 | 支持多種數據源 | 支持多種數據源 | 有限支持 |
| 擴展性 | 多個擴展點 | 插件的形式 | 接口的形式 |
| 基于注解的支持 | 支持 | 支持 | 支持 |
| 限流 | 基于 QPS,支持基于調用關系的限流 | 有限的支持 | Rate Limiter |
| 流量整形 | 支持預熱模式、勻速器模式、預熱排隊模式 | 不支持 | 簡單的 Rate Limiter 模式 |
| 系統自適應保護 | 支持 | 不支持 | 不支持 |
| 控制臺 | 提供開箱即用的控制臺,可配置規則、查看秒級監控、機器發現等 | 簡單的監控查看 | 不提供控制臺,可對接其它監控系統 |
目前 Sentinel 在?Spring Cloud Alibaba 項目中已經適配了 Spring Cloud 體系,可以用來完全替代 Hystrix 的功能了。
Spring Cloud Alibaba Sentinel 功能介紹
Spring Cloud Alibaba Sentinel 主要是為了整合 Sentinel 和 Spring Boot/Cloud 技術棧。目前完成了如下功能:
Spring Cloud Alibaba Sentinel 代替 Hystrix
想要使用 Spring Cloud Alibaba Sentinel,需要加上依賴信息:
<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>把 hystrix 的配置改成 sentinel 的即可使用 Sentinel 的限流降級功能:
# 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。
只需配置這些規則,限流降級操作即可立即生效。
一行代碼支持 RestTemplate
Sentinel 還跟 Spring 生態的?RestTemplate?做了整合,可以對?RestTemplate?請求過程進行限流和降級操作,只需要在構造 RestTemplate 的時候加上?@SentinelRestTemplate?注解即可:
@Bean @SentinelRestTemplate public RestTemplate restTemplate() {return new RestTemplate(); }@SentinelRestTemplate?注解還暴露出了對應的屬性可進行限流降級后的自定義錯誤,默認的行為是返回 "RestTemplate request block by sentinel" 信息。
#阿里云開年Hi購季#幸運抽好禮!
點此抽獎:https://www.aliyun.com/acts/product-section-2019/yq-lottery?utm_content=g_1000042901
原文鏈接
本文為云棲社區原創內容,未經允許不得轉載。
總結
以上是生活随笔為你收集整理的Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑科技揭秘:百种异常随机注入,专有云为何
- 下一篇: Spring Cloud Alibaba