Spring Cloud Alibaba Sentinel对RestTemplate的支持

栏目: Java · 发布时间: 6年前

内容简介:Spring Cloud Alibaba Sentinel 支持对 RestTemplate 的服务调用使用 Sentinel 进行保护,在构造 RestTemplate bean的时候需要加上 @SentinelRestTemplate 注解。需要注意的是目前的版本spring-cloud-starter-alibaba-sentinel.0.2.1.RELEASE在配置RestTemplate的时候有个Bug,需要将配置放在Spring Boot的启动类中,也就是@SpringBootApplicati

Spring Cloud Alibaba Sentinel对RestTemplate的支持

Spring Cloud Alibaba Sentinel 支持对 RestTemplate 的服务调用使用 Sentinel 进行保护,在构造 RestTemplate bean的时候需要加上 @SentinelRestTemplate 注解。

需要注意的是目前的版本spring-cloud-starter-alibaba-sentinel.0.2.1.RELEASE在配置RestTemplate的时候有个Bug,需要将配置放在Spring Boot的启动类中,也就是@SpringBootApplication注解所在的类。

如果单独放在@Configuration标记的类中目前是有问题的,当然后续版本中会进行修复,对应的问题描述:

https://github.com/spring-cloud-incubator/spring-cloud-alibaba/issues/227

  • blockHandler 限流后处理的方法

  • blockHandlerClass 限流后处理的类

  • fallback 熔断后处理的方法

  • fallbackClass 熔断后处理的类

异常处理类定义需要注意的是该方法的参数跟返回值跟 org.springframework.http.client.ClientHttpRequestInterceptor#interceptor 方法一致,其中参数多出了一个 BlockException 参数用于获取 Sentinel 捕获的异常。

原理剖析

核心代码在org.springframework.cloud.alibaba.sentinel.custom.SentinelBeanPostProcessor中,实现了MergedBeanDefinitionPostProcessor接口,MergedBeanDefinitionPostProcessor接口实现了BeanPostProcessor接口。

核心方法就是重写的postProcessMergedBeanDefinition和postProcessAfterInitialization。

postProcessMergedBeanDefinition

postProcessAfterInitialization

看到这边大家就明白了,其实就是给restTemplate添加拦截器来处理。跟Ribbon中的@LoadBalanced原理是一样的。

SentinelProtectInterceptor

Sentinel RestTemplate 限流的资源规则提供两种粒度:

  • schema://host:port/path: 协议、主机、端口和路径

  • schema://host:port: 协议、主机和端口

这两种粒度从 org.springframework.cloud.alibaba.sentinel.custom.SentinelProtectInterceptor.intercept(HttpRequest, byte[], ClientHttpRequestExecution) 方法中可以看的出来

下面就是根据hostResource和hostWithPathResource进行限流

在后面就是释放资源,异常处理等代码,大家自己去了解下。

加入星球特权

Spring Cloud Alibaba Sentinel对RestTemplate的支持

1、从前端到后端玩转Spring Cloud

2、实战分库分表中间件Sharding-JDBC

3、实战分布式任务调度框架Elastic Job

4、配置中心Apollo实战

5、高并发解决方案之缓存

6、更多课程等你来解锁,20+课程

Spring Cloud Alibaba Sentinel对RestTemplate的支持


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Haskell

Haskell

Simon Thompson / Addison-Wesley / 1999-3-16 / GBP 40.99

The second edition of Haskell: The Craft of Functional Programming is essential reading for beginners to functional programming and newcomers to the Haskell programming language. The emphasis is on th......一起来看看 《Haskell》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具