自 Spring Cloud 官方宣布 Spring Cloud Netflix 进入维护状态后,我们开始制作《Spring Cloud Alibaba迁移指南》系列文章,向开发者提供更多的技术选型方案,并降低迁移过程中的技术难度。
第一篇,我们对Hystrix、Resilience4j 和 Sentinel 三个开源项目进行对比,并探讨如何使用一行代码这种极简的方式,将Hystrix迁移到Sentinel。
Hystrix 自从前段时间 宣布停止维护之后,社区推荐了 resilience4j。这 3 款产品各有优劣势,具体的功能差异参考下表(该表来源 Sentinel Wiki):
目前 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/...。
只需配置这些规则,限流降级操作即可立即生效。
一行代码支持 RestTemplate
Sentinel 还跟 Spring 生态的 RestTemplate 做了整合,可以对 RestTemplate 请求过程进行限流和降级操作,只需要在构造 RestTemplate 的时候加上 @SentinelRestTemplate 注解即可:
@Bean
@SentinelRestTemplate
public RestTemplate restTemplate() {
return new RestTemplate();
}
@SentinelRestTemplate 注解还暴露出了对应的属性可进行限流降级后的自定义错误,默认的行为是返回 "RestTemplate request block by sentinel" 信息。关于 @SentinelRestTemplate 的详细信息可以参考 Wiki。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。