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