Spring?Cloud?Alibaba微服務(wù)組件Sentinel實現(xiàn)熔斷限流
Sentinel簡介
Spring Cloud Alibaba 致力于提供微服務(wù)開發(fā)的一站式解決方案,Sentinel 作為其核心組件之一,具有熔斷與限流等一系列服務(wù)保護(hù)功能,本文將對其用法進(jìn)行詳細(xì)介紹。
隨著微服務(wù)的流行,服務(wù)和服務(wù)之間的穩(wěn)定性變得越來越重要。Sentinel 以流量為切入點,從流量控制、熔斷降級、系統(tǒng)負(fù)載保護(hù)等多個維度保護(hù)服務(wù)的穩(wěn)定性。
Sentinel具有如下特性:
- 豐富的應(yīng)用場景:承接了阿里巴巴近 10 年的雙十一大促流量的核心場景,例如秒殺,可以實時熔斷下游不可用應(yīng)用;
- 完備的實時監(jiān)控:同時提供實時的監(jiān)控功能??梢栽诳刂婆_中看到接入應(yīng)用的單臺機(jī)器秒級數(shù)據(jù),甚至 500 臺以下規(guī)模的集群的匯總運行情況;
- 廣泛的開源生態(tài):提供開箱即用的與其它開源框架/庫的整合模塊,例如與 Spring Cloud、Dubbo、gRPC 的整合;
- 完善的 SPI 擴(kuò)展點:提供簡單易用、完善的 SPI 擴(kuò)展點。您可以通過實現(xiàn)擴(kuò)展點,快速的定制邏輯。
安裝Sentinel控制臺
Sentinel控制臺是一個輕量級的控制臺應(yīng)用,它可用于實時查看單機(jī)資源監(jiān)控及集群資源匯總,并提供了一系列的規(guī)則管理功能,如流控規(guī)則、降級規(guī)則、熱點規(guī)則等。
我們先從官網(wǎng)下載Sentinel,這里下載的是sentinel-dashboard-1.6.3.jar文件,
下載地址:https://github.com/alibaba/Sentinel/releases
下載完成后在命令行輸入如下命令運行Sentinel控制臺:
java -jar sentinel-dashboard-1.6.3.jar
Sentinel控制臺默認(rèn)運行在8080端口上,登錄賬號密碼均為 sentinel
,通過如下地址可以進(jìn)行訪問:http://localhost:8080
Sentinel控制臺可以查看單臺機(jī)器的實時監(jiān)控數(shù)據(jù)。
創(chuàng)建sentinel-service模塊
這里我們創(chuàng)建一個sentinel-service模塊,用于演示Sentinel的熔斷與限流功能。
在pom.xml中添加相關(guān)依賴,這里我們使用Nacos作為注冊中心,所以需要同時添加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控制臺的地址:
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ù)提供了限流埋點,我們也可以通過使用@SentinelResource來自定義一些限流行為。
創(chuàng)建RateLimitController類
用于測試熔斷和限流功能。
/** * 限流功能 * 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控制臺進(jìn)行配置,由于我們使用了Nacos注冊中心,我們先啟動Nacos和sentinel-service;
- 由于Sentinel采用的懶加載規(guī)則,需要我們先訪問下接口,Sentinel控制臺中才會有對應(yīng)服務(wù)信息,我們先訪問下該接口:http://localhost:8401/rateLimit/byResource
- 在Sentinel控制臺配置流控規(guī)則,根據(jù)@SentinelResource注解的value值:
快速訪問上面的接口,可以發(fā)現(xiàn)返回了自己定義的限流處理信息:
根據(jù)URL限流
我們還可以通過訪問的URL來限流,會返回默認(rèn)的限流處理信息。
在Sentinel控制臺配置流控規(guī)則,使用訪問的URL:
多次訪問該接口,會返回默認(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 支持對服務(wù)間調(diào)用進(jìn)行保護(hù),對故障應(yīng)用進(jìn)行熔斷操作,這里我們使用RestTemplate來調(diào)用nacos-user-service服務(wù)所提供的接口來演示下該功能。
首先我們需要使用@SentinelRestTemplate來包裝下RestTemplate實例:
/** * Created by macro on 2019/8/29. */ @Configuration public class RibbonConfig { @Bean @SentinelRestTemplate public RestTemplate restTemplate(){ return new RestTemplate(); } }
添加CircleBreakerController類,定義對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ù)降級返回",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ù)降級返回",200); } }
啟動nacos-user-service和sentinel-service服務(wù):
由于我們并沒有在nacos-user-service中定義id為4的用戶,所有訪問如下接口會返回服務(wù)降級結(jié)果:http://localhost:8401/breaker/fallback/4
{ "data": { "id": -1, "username": "defaultUser", "password": "123456" }, "message": "服務(wù)降級返回", "code": 200 }
由于我們使用了exceptionsToIgnore參數(shù)忽略了NullPointerException,所以我們訪問接口報空指針時不會發(fā)生服務(wù)降級:http://localhost:8401/breaker/fallbackException/2
與Feign結(jié)合使用
Sentinel也適配了Feign組件,我們使用Feign來進(jìn)行服務(wù)間調(diào)用時,也可以使用它來進(jìn)行熔斷。
首先我們需要在pom.xml中添加Feign相關(guān)依賴:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
在application.yml中打開Sentinel對Feign的支持:
feign: sentinel: enabled: true #打開sentinel對feign的支持
在應(yīng)用啟動類上添加@EnableFeignClients啟動Feign的功能;
創(chuàng)建一個UserService接口,用于定義對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類實現(xiàn)UserService接口,用于處理服務(wù)降級邏輯:
/** * 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ù)降級返回",200); } @Override public CommonResult<User> getUser(Long id) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser,"服務(wù)降級返回",200); } @Override public CommonResult<User> getByUsername(String username) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser,"服務(wù)降級返回",200); } @Override public CommonResult update(User user) { return new CommonResult("調(diào)用失敗,服務(wù)被降級",500); } @Override public CommonResult delete(Long id) { return new CommonResult("調(diào)用失敗,服務(wù)被降級",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)用如下接口會發(fā)生服務(wù)降級,返回服務(wù)降級處理信息:http://localhost:8401/user/4
{ "data": { "id": -1, "username": "defaultUser", "password": "123456" }, "message": "服務(wù)降級返回", "code": 200 }
使用Nacos存儲規(guī)則
默認(rèn)情況下,當(dāng)我們在Sentinel控制臺中配置規(guī)則時,控制臺推送規(guī)則方式是通過API將規(guī)則推送至客戶端并直接更新到內(nèi)存中。一旦我們重啟應(yīng)用,規(guī)則將消失。下面我們介紹下如何將配置規(guī)則進(jìn)行持久化,以存儲到Nacos為例。
原理示意圖
首先我們直接在配置中心創(chuàng)建規(guī)則,配置中心將規(guī)則推送到客戶端;
Sentinel控制臺也從配置中心去獲取配置信息。
功能演示
先在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:單機(jī)閾值;
- strategy:流控模式,0表示直接,1表示關(guān)聯(lián),2表示鏈路;
- controlBehavior:流控效果,0表示快速失敗,1表示W(wǎng)arm Up,2表示排隊等待;
clusterMode:是否集群。
發(fā)現(xiàn)Sentinel控制臺已經(jīng)有了如下限流規(guī)則:
快速訪問測試接口,可以發(fā)現(xiàn)返回了限流處理信息:
參考資料
Spring Cloud Alibaba 官方文檔:https://github.com/alibaba/spring-cloud-alibaba/wiki
使用到的模塊
springcloud-learning ├── nacos-user-service -- 注冊到nacos的提供User對象CRUD接口的服務(wù) └── sentinel-service -- sentinel功能測試服務(wù)
項目源碼地址
https://github.com/macrozheng/springcloud-learning
以上就是Spring Cloud Alibaba微服務(wù)組件Sentinel實現(xiàn)熔斷限流的詳細(xì)內(nèi)容,更多關(guān)于Spring Cloud Sentinel熔斷限流的資料請關(guān)注腳本之家其它相關(guān)文章!
- 在SpringBoot項目中使用Spring Cloud Sentinel實現(xiàn)流量控制
- SpringCloud?集成Sentinel的實戰(zhàn)教程
- Spring?Cloud?中使用?Sentinel?實現(xiàn)服務(wù)限流的兩種方式
- Spring?Cloud中Sentinel的兩種限流模式介紹
- springcloud3 Sentinel的搭建及案例操作方法
- Spring?Cloud微服務(wù)架構(gòu)Sentinel數(shù)據(jù)雙向同步
- Spring?Cloud?Gateway整合sentinel?實現(xiàn)流控熔斷的問題
- Java之SpringCloudAlibaba Sentinel組件案例講解
- Sentinel 斷路器在Spring Cloud使用詳解
相關(guān)文章
springboot自定義starter啟動器的具體使用實踐
本文主要介紹了springboot自定義starter啟動器的具體使用實踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09java 自己實現(xiàn)DataSource實現(xiàn)實例
這篇文章主要介紹了java 自己實現(xiàn)DataSource實現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05Spring Cloud Feign實例講解學(xué)習(xí)
這篇文章主要介紹了Spring Cloud Feign實例講解學(xué)習(xí),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02Spring Boot啟動過程(五)之Springboot內(nèi)嵌Tomcat對象的start教程詳解
這篇文章主要介紹了Spring Boot啟動過程(五)之Springboot內(nèi)嵌Tomcat對象的start的相關(guān)資料,需要的朋友可以參考下2017-04-04淺談Ribbon、Feign和OpenFeign的區(qū)別
這篇文章主要介紹了淺談Ribbon、Feign和OpenFeign的區(qū)別。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06