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