Spring Cloud Alibaba Sentinel 是阿里巴巴提供的,致力于提供微服務(wù)一站式解決方案,Spring Cloud Alibaba 默認為 Sentinel 整合了,ServeLet、RestTemplate、FeignClient 和 Spring Flux。在 Spring 的生態(tài)中不僅不全了 Hystrix 在 ServeLet 和 RestTemplate 這一塊的空白,而且還完美的兼容了 Hystrix 在 Feign 中的限流降級用法,并支持運行時靈活的配置和調(diào)整限流降級規(guī)則。
引入依賴:
1
2
3
4
5
6
|
<!--Sentinel 整合SpringCloud 的依賴--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel</artifactId> <version> 2.2 . 0 .RELEASE</version> </dependency> |
配置文件:
(入門使用中,應(yīng)用名稱使用的 JVM 參數(shù)設(shè)置的,整合 SpringCloud 就不需要那樣了,配置文件中配置了應(yīng)用的名稱后,Sentinel 會自動加載)
1
2
3
4
5
6
7
8
9
10
|
# 設(shè)置應(yīng)用的名稱 spring: application: name: springCloudSentinel cloud: sentinel: transport: #設(shè)置Sentinel控制臺的主機地址和端口號 dashboard: localhost: 9000 |
編寫測試 Controller ,控制臺添加 Sentinel_Cloud 資源 限流測試
1
2
3
4
5
6
|
@SentinelResource (value = "Sentinel_Cloud" ,blockHandler = "exceptionHandler" ) @GetMapping ( "/sentinelCloud" ) public String sentinelCloud(){ //使用限流規(guī)則 return "Sentinel_Cloud,成功調(diào)用" ; } |
限流時調(diào)用的方法:
1
2
3
4
5
6
7
8
9
10
|
/** * 定義降級 / 限流 的處理函數(shù) * * @param exception * @return */ public String exceptionHandler(BlockException exception) { exception.printStackTrace(); return "Sentinel_Cloud,訪問限流" ; } |
Sentinel整合Feign (OpenFeign)
Sentinel適配了Feign組件。如果想要使用,除了引用spring-cloud-starter-alibaba-sentinel的依賴,還需要兩個步驟:
配置打開Sentinel對Feign的支持:feign.sentinel.enable=true
加入spring-cloud-starter-openfeign依賴使Sentinel starter自動化配置類生效。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# 設(shè)置應(yīng)用的名稱 spring: application: name: springCloudSentinel cloud: sentinel: transport: #設(shè)置Sentinel控制臺的主機地址和端口號 dashboard: localhost: 9000 # 開啟 Sentinel 對 Feign 的支持 feign: sentinel: enabled: true |
服務(wù)端調(diào)用方Controller
1
2
3
4
|
@GetMapping ( "/feignHello" ) public String feignHello(){ return feignClient.feignHello(); } |
服務(wù)提供方 FeignClient
1
2
3
4
5
6
7
8
9
10
11
|
@FeignClient (contextId = "testFeignClient" , value = "注冊中心中服務(wù)的名稱" , fallback = FeignFallbackService. class ) public interface TestFeignClient { /** * OpenFeign 遠程調(diào)用的方法 * * @return */ @GetMapping ( "/test/feignHello" ) String feignHello(); } |
提供一個 FeignClient 接口的實現(xiàn)類,作為限流的處理方法
1
2
3
4
5
6
7
|
@Service public class FeignFallbackService implements TestFeignClient{ @Override public String feignHello() { return "Feign 遠程調(diào)用限流了" ; } } |
Sentinel 控制臺添加限流規(guī)則:
請求方式:http://服務(wù)模塊注冊中心名稱/test/feignHello
到此這篇關(guān)于Sentinel 之 整合SpringCloud的文章就介紹到這了,更多相關(guān)Sentinel 整合SpringCloud內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/Alay/p/15488116.html