Spring Cloud Alibaba:Sentinel實(shí)現(xiàn)熔斷與限流

Spring Cloud Alibaba:Sentinel實(shí)現(xiàn)熔斷與限流

Spring Cloud Alibaba 致力于提供微服務(wù)開(kāi)發(fā)的一站式解決方案,Sentinel 作為其核心組件之一,具有熔斷與限流等一系列服務(wù)保護(hù)功能,本文將對(duì)其用法進(jìn)行詳細(xì)介紹。

Sentinel簡(jiǎn)介

隨著微服務(wù)的流行,服務(wù)和服務(wù)之間的穩(wěn)定性變得越來(lái)越重要。 Sentinel 以流量為切入點(diǎn),從流量控制、熔斷降級(jí)、系統(tǒng)負(fù)載保護(hù)等多個(gè)維度保護(hù)服務(wù)的穩(wěn)定性。

Sentinel具有如下特性:

豐富的應(yīng)用場(chǎng)景:承接了阿里巴巴近 10 年的雙十一大促流量的核心場(chǎng)景,例如秒殺,可以實(shí)時(shí)熔斷下游不可用應(yīng)用;

完備的實(shí)時(shí)監(jiān)控:同時(shí)提供實(shí)時(shí)的監(jiān)控功能??梢栽诳刂婆_(tái)中看到接入應(yīng)用的單臺(tái)機(jī)器秒級(jí)數(shù)據(jù),甚至 500 臺(tái)以下規(guī)模的集群的匯總運(yùn)行情況;

廣泛的開(kāi)源生態(tài):提供開(kāi)箱即用的與其它開(kāi)源框架/庫(kù)的整合模塊,例如與 Spring Cloud、Dubbo、gRPC 的整合;

完善的 SPI 擴(kuò)展點(diǎn):提供簡(jiǎn)單易用、完善的 SPI 擴(kuò)展點(diǎn)。您可以通過(guò)實(shí)現(xiàn)擴(kuò)展點(diǎn),快速的定制邏輯。

安裝Sentinel控制臺(tái)

Sentinel控制臺(tái)是一個(gè)輕量級(jí)的控制臺(tái)應(yīng)用,它可用于實(shí)時(shí)查看單機(jī)資源監(jiān)控及集群資源匯總,并提供了一系列的規(guī)則管理功能,如流控規(guī)則、降級(jí)規(guī)則、熱點(diǎn)規(guī)則等。

我們先從官網(wǎng)下載Sentinel,這里下載的是sentinel-dashboard-1.6.3.jar文件,下載地址:https://github.com/alibaba/Sentinel/releases

下載完成后在命令行輸入如下命令運(yùn)行Sentinel控制臺(tái):

java -jar sentinel-dashboard-1.6.3.jarCopy to clipboardErrorCopied

Sentinel控制臺(tái)默認(rèn)運(yùn)行在8080端口上,登錄賬號(hào)密碼均為sentinel,通過(guò)如下地址可以進(jìn)行訪問(wèn):http://localhost:8080

Sentinel控制臺(tái)可以查看單臺(tái)機(jī)器的實(shí)時(shí)監(jiān)控?cái)?shù)據(jù)。

創(chuàng)建sentinel-service模塊

這里我們創(chuàng)建一個(gè)sentinel-service模塊,用于演示Sentinel的熔斷與限流功能。

在pom.xml中添加相關(guān)依賴(lài),這里我們使用Nacos作為注冊(cè)中心,所以需要同時(shí)添加Nacos的依賴(lài):

<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency>Copy to clipboardErrorCopied

在application.yml中添加相關(guān)配置,主要是配置了Nacos和Sentinel控制臺(tái)的地址:

server:

? port: 8401

spring:

? application:

? ? name: sentinel-service

? cloud:

? ? nacos:

? ? ? discovery:

? ? ? ? server-addr: localhost:8848 #配置Nacos地址

? ? sentinel:

? ? ? transport:

? ? ? ? dashboard: localhost:8080 #配置sentinel dashboard地址

? ? ? ? port: 8719

service-url:

? user-service: http://nacos-user-service

management:

? endpoints:

? ? web:

? ? ? exposure:

? ? ? ? include: '*'Copy to clipboardErrorCopied

限流功能

Sentinel Starter 默認(rèn)為所有的 HTTP 服務(wù)提供了限流埋點(diǎn),我們也可以通過(guò)使用@SentinelResource來(lái)自定義一些限流行為。

創(chuàng)建RateLimitController類(lèi)

用于測(cè)試熔斷和限流功能。

/**

* 限流功能

* Created by macro on 2019/11/7.

*/@RestController@RequestMapping("/rateLimit")publicclassRateLimitController{/**

? ? * 按資源名稱(chēng)限流,需要指定限流處理邏輯

? ? */@GetMapping("/byResource")@SentinelResource(value="byResource",blockHandler="handleException")publicCommonResultbyResource(){returnnewCommonResult("按資源名稱(chēng)限流",200);}/**

? ? * 按URL限流,有默認(rèn)的限流處理邏輯

? ? */@GetMapping("/byUrl")@SentinelResource(value="byUrl",blockHandler="handleException")publicCommonResultbyUrl(){returnnewCommonResult("按url限流",200);}publicCommonResulthandleException(BlockExceptionexception){returnnewCommonResult(exception.getClass().getCanonicalName(),200);}}Copy to clipboardErrorCopied

根據(jù)資源名稱(chēng)限流

我們可以根據(jù)@SentinelResource注解中定義的value(資源名稱(chēng))來(lái)進(jìn)行限流操作,但是需要指定限流處理邏輯。

流控規(guī)則可以在Sentinel控制臺(tái)進(jìn)行配置,由于我們使用了Nacos注冊(cè)中心,我們先啟動(dòng)Nacos和sentinel-service;

由于Sentinel采用的懶加載規(guī)則,需要我們先訪問(wèn)下接口,Sentinel控制臺(tái)中才會(huì)有對(duì)應(yīng)服務(wù)信息,我們先訪問(wèn)下該接口:http://localhost:8401/rateLimit/byResource

在Sentinel控制臺(tái)配置流控規(guī)則,根據(jù)@SentinelResource注解的value值:

快速訪問(wèn)上面的接口,可以發(fā)現(xiàn)返回了自己定義的限流處理信息:

根據(jù)URL限流

我們還可以通過(guò)訪問(wèn)的URL來(lái)限流,會(huì)返回默認(rèn)的限流處理信息。

在Sentinel控制臺(tái)配置流控規(guī)則,使用訪問(wèn)的URL:

多次訪問(wèn)該接口,會(huì)返回默認(rèn)的限流處理結(jié)果:http://localhost:8401/rateLimit/byUrl

自定義限流處理邏輯

我們可以自定義通用的限流處理邏輯,然后在@SentinelResource中指定。

創(chuàng)建CustomBlockHandler類(lèi)用于自定義限流處理邏輯:

/**

* Created by macro on 2019/11/7.

*/publicclassCustomBlockHandler{publicCommonResulthandleException(BlockExceptionexception){returnnewCommonResult("自定義限流信息",200);}}Copy to clipboardErrorCopied

在RateLimitController中使用自定義限流處理邏輯:

/**

* 限流功能

* Created by macro on 2019/11/7.

*/@RestController@RequestMapping("/rateLimit")publicclassRateLimitController{/**

? ? * 自定義通用的限流處理邏輯

? ? */@GetMapping("/customBlockHandler")@SentinelResource(value="customBlockHandler",blockHandler="handleException",blockHandlerClass=CustomBlockHandler.class)publicCommonResultblockHandler(){returnnewCommonResult("限流成功",200);}}Copy to clipboardErrorCopied

熔斷功能

Sentinel 支持對(duì)服務(wù)間調(diào)用進(jìn)行保護(hù),對(duì)故障應(yīng)用進(jìn)行熔斷操作,這里我們使用RestTemplate來(lái)調(diào)用nacos-user-service服務(wù)所提供的接口來(lái)演示下該功能。

首先我們需要使用@SentinelRestTemplate來(lái)包裝下RestTemplate實(shí)例:

/**

* Created by macro on 2019/8/29.

*/@ConfigurationpublicclassRibbonConfig{@Bean@SentinelRestTemplatepublicRestTemplaterestTemplate(){returnnewRestTemplate();}}Copy to clipboardErrorCopied

添加CircleBreakerController類(lèi),定義對(duì)nacos-user-service提供接口的調(diào)用:

/**

* 熔斷功能

* Created by macro on 2019/11/7.

*/@RestController@RequestMapping("/breaker")publicclassCircleBreakerController{privateLoggerLOGGER=LoggerFactory.getLogger(CircleBreakerController.class);@AutowiredprivateRestTemplaterestTemplate;@Value("${service-url.user-service}")privateStringuserServiceUrl;@RequestMapping("/fallback/{id}")@SentinelResource(value="fallback",fallback="handleFallback")publicCommonResultfallback(@PathVariableLongid){returnrestTemplate.getForObject(userServiceUrl+"/user/{1}",CommonResult.class,id);}@RequestMapping("/fallbackException/{id}")@SentinelResource(value="fallbackException",fallback="handleFallback2",exceptionsToIgnore={NullPointerException.class})publicCommonResultfallbackException(@PathVariableLongid){if(id==1){thrownewIndexOutOfBoundsException();}elseif(id==2){thrownewNullPointerException();}returnrestTemplate.getForObject(userServiceUrl+"/user/{1}",CommonResult.class,id);}publicCommonResulthandleFallback(Longid){UserdefaultUser=newUser(-1L,"defaultUser","123456");returnnewCommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200);}publicCommonResulthandleFallback2(@PathVariableLongid,Throwablee){LOGGER.error("handleFallback2 id:{},throwable class:{}",id,e.getClass());UserdefaultUser=newUser(-2L,"defaultUser2","123456");returnnewCommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200);}}Copy to clipboardErrorCopied

啟動(dòng)nacos-user-service和sentinel-service服務(wù):

由于我們并沒(méi)有在nacos-user-service中定義id為4的用戶,所有訪問(wèn)如下接口會(huì)返回服務(wù)降級(jí)結(jié)果:http://localhost:8401/breaker/fallback/4

{

? ? "data": {

? ? ? ? "id": -1,

? ? ? ? "username": "defaultUser",

? ? ? ? "password": "123456"

? ? },

? ? "message": "服務(wù)降級(jí)返回",

? ? "code": 200

}Copy to clipboardErrorCopied

由于我們使用了exceptionsToIgnore參數(shù)忽略了NullPointerException,所以我們?cè)L問(wèn)接口報(bào)空指針時(shí)不會(huì)發(fā)生服務(wù)降級(jí):http://localhost:8401/breaker/fallbackException/2

與Feign結(jié)合使用

Sentinel也適配了Feign組件,我們使用Feign來(lái)進(jìn)行服務(wù)間調(diào)用時(shí),也可以使用它來(lái)進(jìn)行熔斷。

首先我們需要在pom.xml中添加Feign相關(guān)依賴(lài):

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>Copy to clipboardErrorCopied

在application.yml中打開(kāi)Sentinel對(duì)Feign的支持:

feign:

? sentinel:

? ? enabled: true #打開(kāi)sentinel對(duì)feign的支持Copy to clipboardErrorCopied

在應(yīng)用啟動(dòng)類(lèi)上添加@EnableFeignClients啟動(dòng)Feign的功能;

創(chuàng)建一個(gè)UserService接口,用于定義對(duì)nacos-user-service服務(wù)的調(diào)用:

/**

* Created by macro on 2019/9/5.

*/@FeignClient(value="nacos-user-service",fallback=UserFallbackService.class)publicinterfaceUserService{@PostMapping("/user/create")CommonResultcreate(@RequestBodyUseruser);@GetMapping("/user/{id}")CommonResult<User>getUser(@PathVariableLongid);@GetMapping("/user/getByUsername")CommonResult<User>getByUsername(@RequestParamStringusername);@PostMapping("/user/update")CommonResultupdate(@RequestBodyUseruser);@PostMapping("/user/delete/{id}")CommonResultdelete(@PathVariableLongid);}Copy to clipboardErrorCopied

創(chuàng)建UserFallbackService類(lèi)實(shí)現(xiàn)UserService接口,用于處理服務(wù)降級(jí)邏輯:

/**

* Created by macro on 2019/9/5.

*/@ComponentpublicclassUserFallbackServiceimplementsUserService{@OverridepublicCommonResultcreate(Useruser){UserdefaultUser=newUser(-1L,"defaultUser","123456");returnnewCommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200);}@OverridepublicCommonResult<User>getUser(Longid){UserdefaultUser=newUser(-1L,"defaultUser","123456");returnnewCommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200);}@OverridepublicCommonResult<User>getByUsername(Stringusername){UserdefaultUser=newUser(-1L,"defaultUser","123456");returnnewCommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200);}@OverridepublicCommonResultupdate(Useruser){returnnewCommonResult("調(diào)用失敗,服務(wù)被降級(jí)",500);}@OverridepublicCommonResultdelete(Longid){returnnewCommonResult("調(diào)用失敗,服務(wù)被降級(jí)",500);}}Copy to clipboardErrorCopied

在UserFeignController中使用UserService通過(guò)Feign調(diào)用nacos-user-service服務(wù)中的接口:

/**

* Created by macro on 2019/8/29.

*/@RestController@RequestMapping("/user")publicclassUserFeignController{@AutowiredprivateUserServiceuserService;@GetMapping("/{id}")publicCommonResultgetUser(@PathVariableLongid){returnuserService.getUser(id);}@GetMapping("/getByUsername")publicCommonResultgetByUsername(@RequestParamStringusername){returnuserService.getByUsername(username);}@PostMapping("/create")publicCommonResultcreate(@RequestBodyUseruser){returnuserService.create(user);}@PostMapping("/update")publicCommonResultupdate(@RequestBodyUseruser){returnuserService.update(user);}@PostMapping("/delete/{id}")publicCommonResultdelete(@PathVariableLongid){returnuserService.delete(id);}}Copy to clipboardErrorCopied

調(diào)用如下接口會(huì)發(fā)生服務(wù)降級(jí),返回服務(wù)降級(jí)處理信息:http://localhost:8401/user/4

{

? ? "data": {

? ? ? ? "id": -1,

? ? ? ? "username": "defaultUser",

? ? ? ? "password": "123456"

? ? },

? ? "message": "服務(wù)降級(jí)返回",

? ? "code": 200

}Copy to clipboardErrorCopied

使用Nacos存儲(chǔ)規(guī)則

默認(rèn)情況下,當(dāng)我們?cè)赟entinel控制臺(tái)中配置規(guī)則時(shí),控制臺(tái)推送規(guī)則方式是通過(guò)API將規(guī)則推送至客戶端并直接更新到內(nèi)存中。一旦我們重啟應(yīng)用,規(guī)則將消失。下面我們介紹下如何將配置規(guī)則進(jìn)行持久化,以存儲(chǔ)到Nacos為例。

原理示意圖

首先我們直接在配置中心創(chuàng)建規(guī)則,配置中心將規(guī)則推送到客戶端;

Sentinel控制臺(tái)也從配置中心去獲取配置信息。

功能演示

先在pom.xml中添加相關(guān)依賴(lài):

<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId></dependency>Copy to clipboardErrorCopied

修改application.yml配置文件,添加Nacos數(shù)據(jù)源配置:

spring:

? cloud:

? ? sentinel:

? ? ? datasource:

? ? ? ? ds1:

? ? ? ? ? nacos:

? ? ? ? ? ? server-addr: localhost:8848

? ? ? ? ? ? dataId: ${spring.application.name}-sentinel

? ? ? ? ? ? groupId: DEFAULT_GROUP

? ? ? ? ? ? data-type: json

? ? ? ? ? ? rule-type: flowCopy to clipboardErrorCopied

在Nacos中添加配置:

添加配置信息如下:

[

? ? {

? ? ? ? "resource": "/rateLimit/byUrl",

? ? ? ? "limitApp": "default",

? ? ? ? "grade": 1,

? ? ? ? "count": 1,

? ? ? ? "strategy": 0,

? ? ? ? "controlBehavior": 0,

? ? ? ? "clusterMode": false

? ? }

]Copy to clipboardErrorCopied

相關(guān)參數(shù)解釋?zhuān)?/p>

resource:資源名稱(chēng);

limitApp:來(lái)源應(yīng)用;

grade:閾值類(lèi)型,0表示線程數(shù),1表示QPS;

count:?jiǎn)螜C(jī)閾值;

strategy:流控模式,0表示直接,1表示關(guān)聯(lián),2表示鏈路;

controlBehavior:流控效果,0表示快速失敗,1表示W(wǎng)arm Up,2表示排隊(duì)等待;

clusterMode:是否集群。

發(fā)現(xiàn)Sentinel控制臺(tái)已經(jīng)有了如下限流規(guī)則:

快速訪問(wèn)測(cè)試接口,可以發(fā)現(xiàn)返回了限流處理信息:

參考資料

Spring Cloud Alibaba 官方文檔:https://github.com/alibaba/spring-cloud-alibaba/wiki

使用到的模塊

springcloud-learning

├── nacos-user-service -- 注冊(cè)到nacos的提供User對(duì)象CRUD接口的服務(wù)

└── sentinel-service -- sentinel功能測(cè)試服務(wù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容