Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
时间: 2019-02-27来源:OSCHINA
前景提要
【围观】麒麟芯片遭打压成绝版,华为亿元投入又砸向了哪里?>>>
自 Spring Cloud 官方宣布 Spring Cloud Netflix 进入维护状态后,我们开始制作 《Spring Cloud Alibaba迁移指南》 系列文章,向开发者提供更多的技术选型方案,并降低迁移过程中的技术难度。
第一篇,我们对Hystrix、Resilience4j 和 Sentinel 三个开源项目进行对比,并探讨如何使用一行代码这种极简的方式,将Hystrix迁移到Sentinel。
Hystrix 自从前段时间 宣布停止维护 之后,社区推荐了 resilience4j 。这 3 款产品各有优劣势,具体的功能差异参考下表(该表来源 Sentinel Wiki ):
SentinelHystrixresilience4j隔离策略信号量隔离(并发线程数限流)线程池隔离/信号量隔离信号量隔离熔断降级策略基于响应时间、异常比率、异常数基于异常比率基于异常比率、响应时间实时统计实现滑动窗口(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 技术栈。目前完成了如下功能: 自动适配 Servlet 容器。只需要配置 url-pattern(默认拦截所有请求),即可对拦截的这些 url 进行限流降级操作 整合了 RestTemplate,使用 RestTemplate 进行操作的时候会被限流降级 整合了 Feign,兼容了原先的 Hystrix 支持 Feign 的编程模型 数据源可配置化,只需在配置文件中配置数据源信息,即可动态加载规则 Endpoint 暴露各种元数据,比如配置信息,规则数据 HealthIndicator 检查 Sentinel 健康状态 (整合中) 支持 Spring Cloud Gateway 和 Zuul (整合中)
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购季#幸运抽好礼!
点此抽奖: 【阿里云】开年Hi购季,幸运抽好礼

原文链接
本文为云栖社区原创内容,未经允许不得转载。

科技资讯:

科技学院:

科技百科:

科技书籍:

网站大全:

软件大全:

热门排行