Spring?Cloud?Alibaba微服務(wù)組件Sentinel實(shí)現(xiàn)熔斷限流
Sentinel簡(jiǎn)介
Spring Cloud Alibaba 致力于提供微服務(wù)開發(fā)的一站式解決方案,Sentinel 作為其核心組件之一,具有熔斷與限流等一系列服務(wù)保護(hù)功能,本文將對(duì)其用法進(jìn)行詳細(xì)介紹。
隨著微服務(wù)的流行,服務(wù)和服務(wù)之間的穩(wěn)定性變得越來越重要。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)行情況;
- 廣泛的開源生態(tài):提供開箱即用的與其它開源框架/庫(kù)的整合模塊,例如與 Spring Cloud、Dubbo、gRPC 的整合;
- 完善的 SPI 擴(kuò)展點(diǎn):提供簡(jiǎn)單易用、完善的 SPI 擴(kuò)展點(diǎn)。您可以通過實(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.jar
Sentinel控制臺(tái)默認(rèn)運(yùn)行在8080端口上,登錄賬號(hào)密碼均為 sentinel
,通過如下地址可以進(jì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)依賴,這里我們使用Nacos作為注冊(cè)中心,所以需要同時(shí)添加Nacos的依賴:
<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>
在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: '*'
限流功能
Sentinel Starter 默認(rèn)為所有的 HTTP 服務(wù)提供了限流埋點(diǎn),我們也可以通過使用@SentinelResource來自定義一些限流行為。
創(chuàng)建RateLimitController類
用于測(cè)試熔斷和限流功能。
/** * 限流功能 * Created by macro on 2019/11/7. */ @RestController @RequestMapping("/rateLimit") public class RateLimitController { /** * 按資源名稱限流,需要指定限流處理邏輯 */ @GetMapping("/byResource") @SentinelResource(value = "byResource",blockHandler = "handleException") public CommonResult byResource() { return new CommonResult("按資源名稱限流", 200); } /** * 按URL限流,有默認(rèn)的限流處理邏輯 */ @GetMapping("/byUrl") @SentinelResource(value = "byUrl",blockHandler = "handleException") public CommonResult byUrl() { return new CommonResult("按url限流", 200); } public CommonResult handleException(BlockException exception){ return new CommonResult(exception.getClass().getCanonicalName(),200); } }
根據(jù)資源名稱限流
我們可以根據(jù)@SentinelResource注解中定義的value(資源名稱)來進(jìn)行限流操作,但是需要指定限流處理邏輯。
- 流控規(guī)則可以在Sentinel控制臺(tái)進(jìn)行配置,由于我們使用了Nacos注冊(cè)中心,我們先啟動(dòng)Nacos和sentinel-service;
- 由于Sentinel采用的懶加載規(guī)則,需要我們先訪問下接口,Sentinel控制臺(tái)中才會(huì)有對(duì)應(yīng)服務(wù)信息,我們先訪問下該接口:http://localhost:8401/rateLimit/byResource
- 在Sentinel控制臺(tái)配置流控規(guī)則,根據(jù)@SentinelResource注解的value值:
快速訪問上面的接口,可以發(fā)現(xiàn)返回了自己定義的限流處理信息:
根據(jù)URL限流
我們還可以通過訪問的URL來限流,會(huì)返回默認(rèn)的限流處理信息。
在Sentinel控制臺(tái)配置流控規(guī)則,使用訪問的URL:
多次訪問該接口,會(huì)返回默認(rèn)的限流處理結(jié)果:http://localhost:8401/rateLimit/byUrl
自定義限流處理邏輯
我們可以自定義通用的限流處理邏輯,然后在@SentinelResource中指定。
創(chuàng)建CustomBlockHandler類用于自定義限流處理邏輯:
/** * Created by macro on 2019/11/7. */ public class CustomBlockHandler { public CommonResult handleException(BlockException exception){ return new CommonResult("自定義限流信息",200); } }
在RateLimitController中使用自定義限流處理邏輯:
/** * 限流功能 * Created by macro on 2019/11/7. */ @RestController @RequestMapping("/rateLimit") public class RateLimitController { /** * 自定義通用的限流處理邏輯 */ @GetMapping("/customBlockHandler") @SentinelResource(value = "customBlockHandler", blockHandler = "handleException",blockHandlerClass = CustomBlockHandler.class) public CommonResult blockHandler() { return new CommonResult("限流成功", 200); } }
熔斷功能
Sentinel 支持對(duì)服務(wù)間調(diào)用進(jìn)行保護(hù),對(duì)故障應(yīng)用進(jìn)行熔斷操作,這里我們使用RestTemplate來調(diào)用nacos-user-service服務(wù)所提供的接口來演示下該功能。
首先我們需要使用@SentinelRestTemplate來包裝下RestTemplate實(shí)例:
/** * Created by macro on 2019/8/29. */ @Configuration public class RibbonConfig { @Bean @SentinelRestTemplate public RestTemplate restTemplate(){ return new RestTemplate(); } }
添加CircleBreakerController類,定義對(duì)nacos-user-service提供接口的調(diào)用:
/** * 熔斷功能 * Created by macro on 2019/11/7. */ @RestController @RequestMapping("/breaker") public class CircleBreakerController { private Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class); @Autowired private RestTemplate restTemplate; @Value("${service-url.user-service}") private String userServiceUrl; @RequestMapping("/fallback/{id}") @SentinelResource(value = "fallback",fallback = "handleFallback") public CommonResult fallback(@PathVariable Long id) { return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id); } @RequestMapping("/fallbackException/{id}") @SentinelResource(value = "fallbackException",fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class}) public CommonResult fallbackException(@PathVariable Long id) { if (id == 1) { throw new IndexOutOfBoundsException(); } else if (id == 2) { throw new NullPointerException(); } return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id); } public CommonResult handleFallback(Long id) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200); } public CommonResult handleFallback2(@PathVariable Long id, Throwable e) { LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass()); User defaultUser = new User(-2L, "defaultUser2", "123456"); return new CommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200); } }
啟動(dòng)nacos-user-service和sentinel-service服務(wù):
由于我們并沒有在nacos-user-service中定義id為4的用戶,所有訪問如下接口會(huì)返回服務(wù)降級(jí)結(jié)果:http://localhost:8401/breaker/fallback/4
{ "data": { "id": -1, "username": "defaultUser", "password": "123456" }, "message": "服務(wù)降級(jí)返回", "code": 200 }
由于我們使用了exceptionsToIgnore參數(shù)忽略了NullPointerException,所以我們?cè)L問接口報(bào)空指針時(shí)不會(huì)發(fā)生服務(wù)降級(jí):http://localhost:8401/breaker/fallbackException/2
與Feign結(jié)合使用
Sentinel也適配了Feign組件,我們使用Feign來進(jìn)行服務(wù)間調(diào)用時(shí),也可以使用它來進(jìn)行熔斷。
首先我們需要在pom.xml中添加Feign相關(guān)依賴:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
在application.yml中打開Sentinel對(duì)Feign的支持:
feign: sentinel: enabled: true #打開sentinel對(duì)feign的支持
在應(yīng)用啟動(dòng)類上添加@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) public interface UserService { @PostMapping("/user/create") CommonResult create(@RequestBody User user); @GetMapping("/user/{id}") CommonResult<User> getUser(@PathVariable Long id); @GetMapping("/user/getByUsername") CommonResult<User> getByUsername(@RequestParam String username); @PostMapping("/user/update") CommonResult update(@RequestBody User user); @PostMapping("/user/delete/{id}") CommonResult delete(@PathVariable Long id); }
創(chuàng)建UserFallbackService類實(shí)現(xiàn)UserService接口,用于處理服務(wù)降級(jí)邏輯:
/** * Created by macro on 2019/9/5. */ @Component public class UserFallbackService implements UserService { @Override public CommonResult create(User user) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200); } @Override public CommonResult<User> getUser(Long id) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200); } @Override public CommonResult<User> getByUsername(String username) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser,"服務(wù)降級(jí)返回",200); } @Override public CommonResult update(User user) { return new CommonResult("調(diào)用失敗,服務(wù)被降級(jí)",500); } @Override public CommonResult delete(Long id) { return new CommonResult("調(diào)用失敗,服務(wù)被降級(jí)",500); } }
在UserFeignController中使用UserService通過Feign調(diào)用nacos-user-service服務(wù)中的接口:
/** * Created by macro on 2019/8/29. */ @RestController @RequestMapping("/user") public class UserFeignController { @Autowired private UserService userService; @GetMapping("/{id}") public CommonResult getUser(@PathVariable Long id) { return userService.getUser(id); } @GetMapping("/getByUsername") public CommonResult getByUsername(@RequestParam String username) { return userService.getByUsername(username); } @PostMapping("/create") public CommonResult create(@RequestBody User user) { return userService.create(user); } @PostMapping("/update") public CommonResult update(@RequestBody User user) { return userService.update(user); } @PostMapping("/delete/{id}") public CommonResult delete(@PathVariable Long id) { return userService.delete(id); } }
調(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 }
使用Nacos存儲(chǔ)規(guī)則
默認(rèn)情況下,當(dāng)我們?cè)赟entinel控制臺(tái)中配置規(guī)則時(shí),控制臺(tái)推送規(guī)則方式是通過API將規(guī)則推送至客戶端并直接更新到內(nèi)存中。一旦我們重啟應(yīng)用,規(guī)則將消失。下面我們介紹下如何將配置規(guī)則進(jìn)行持久化,以存儲(chǔ)到Nacos為例。
原理示意圖
首先我們直接在配置中心創(chuàng)建規(guī)則,配置中心將規(guī)則推送到客戶端;
Sentinel控制臺(tái)也從配置中心去獲取配置信息。
功能演示
先在pom.xml中添加相關(guān)依賴:
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> </dependency>
修改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: flow
在Nacos中添加配置:
添加配置信息如下:
[ { "resource": "/rateLimit/byUrl", "limitApp": "default", "grade": 1, "count": 1, "strategy": 0, "controlBehavior": 0, "clusterMode": false } ]
相關(guān)參數(shù)解釋:
- resource:資源名稱;
- limitApp:來源應(yīng)用;
- grade:閾值類型,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ī)則:
快速訪問測(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ù)
項(xiàng)目源碼地址
https://github.com/macrozheng/springcloud-learning
以上就是Spring Cloud Alibaba微服務(wù)組件Sentinel實(shí)現(xiàn)熔斷限流的詳細(xì)內(nèi)容,更多關(guān)于Spring Cloud Sentinel熔斷限流的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 在SpringBoot項(xiàng)目中使用Spring Cloud Sentinel實(shí)現(xiàn)流量控制
- SpringCloud?集成Sentinel的實(shí)戰(zhàn)教程
- Spring?Cloud?中使用?Sentinel?實(shí)現(xiàn)服務(wù)限流的兩種方式
- Spring?Cloud中Sentinel的兩種限流模式介紹
- springcloud3 Sentinel的搭建及案例操作方法
- Spring?Cloud微服務(wù)架構(gòu)Sentinel數(shù)據(jù)雙向同步
- Spring?Cloud?Gateway整合sentinel?實(shí)現(xiàn)流控熔斷的問題
- Java之SpringCloudAlibaba Sentinel組件案例講解
- Sentinel 斷路器在Spring Cloud使用詳解
相關(guān)文章
Spring?Boot項(xiàng)目傳參校驗(yàn)的最佳實(shí)踐指南
有參數(shù)傳遞的地方都少不了參數(shù)校驗(yàn),在web開發(fā)中前端的參數(shù)校驗(yàn)是為了用戶體驗(yàn),后端的參數(shù)校驗(yàn)是為了安全,下面這篇文章主要給大家介紹了關(guān)于Spring?Boot項(xiàng)目傳參校驗(yàn)的最佳實(shí)踐,需要的朋友可以參考下2022-04-04springboot自定義starter啟動(dòng)器的具體使用實(shí)踐
本文主要介紹了springboot自定義starter啟動(dòng)器的具體使用實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09java 自己實(shí)現(xiàn)DataSource實(shí)現(xiàn)實(shí)例
這篇文章主要介紹了java 自己實(shí)現(xiàn)DataSource實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05Spring Cloud Feign實(shí)例講解學(xué)習(xí)
這篇文章主要介紹了Spring Cloud Feign實(shí)例講解學(xué)習(xí),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-02-02Spring Boot啟動(dòng)過程(五)之Springboot內(nèi)嵌Tomcat對(duì)象的start教程詳解
這篇文章主要介紹了Spring Boot啟動(dòng)過程(五)之Springboot內(nèi)嵌Tomcat對(duì)象的start的相關(guān)資料,需要的朋友可以參考下2017-04-04關(guān)于@Autowired的使用及注意事項(xiàng)
這篇文章主要介紹了關(guān)于@Autowired的使用及注意事項(xiàng),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05淺談Ribbon、Feign和OpenFeign的區(qū)別
這篇文章主要介紹了淺談Ribbon、Feign和OpenFeign的區(qū)別。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06