Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel

自 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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值