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進行限流
在後面就是釋放資源,異常處理等程式碼,大家自己去了解下。
加入星球特權

1、從前端到後端玩轉Spring Cloud
2、實戰分庫分表中介軟體Sharding-JDBC
3、實戰分散式任務排程框架Elastic Job
4、配置中心Apollo實戰
5、高併發解決方案之快取
6、更多課程等你來解鎖,20+課程