自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用 Sentinel 實現(xiàn)接口限流

開發(fā)
本次主要是講 Sentinel 的使用。在 sentinel-dashboard 配置流控規(guī)則,以及使用 Sentinel 整合 RestTemplate、OpenFeign 進行流控使用(建議網(wǎng)頁版閱讀)。

[[399418]]

本文轉(zhuǎn)載自微信公眾號「運維開發(fā)故事」,作者老鄭。轉(zhuǎn)載本文請聯(lián)系運維開發(fā)故事公眾號。

在前面一篇文章我已經(jīng)對 Sentinel 做了一個簡單的介紹,相信大家對 Sentinel 有一個簡單的了解,本次主要是講 Sentinel 的使用。在 sentinel-dashboard 配置流控規(guī)則,以及使用 Sentinel 整合 RestTemplate、OpenFeign 進行流控使用(建議網(wǎng)頁版閱讀)。

安裝 sentinel dashboard

我使用的 sentinel 版本是: sentinel-dashboard-1.8.0

啟動控制臺命令:

  1. java -jar sentinel-dashboard-1.8.0.jar 

默認啟動的是 8080 端口, 登錄賬號和密碼默認都是: sentinel。 如果需要修改啟動端口可以在啟動命令前面加 -Dserver.port=9999 進行修改。

使用介紹

通常我們在項目中對于 Sentinel 最常用的場景,就是默認的流控對接口的訪問添加流控規(guī)則。Sentinel 也提供了對于 RestTemplate 、OpenFegin 的支持。

簡單案例

1. 導(dǎo)入依賴

如果我們需要使用 Sentinel ,首先我們需要在業(yè)務(wù)服務(wù)中,導(dǎo)入 Sentinel 客戶端的依賴。下面是 Maven 的 pom 依賴。 我們可以直接使用 spring-coud-starter-alibaba-sentinel 進行快速整合。

  1. <dependency> 
  2.   <groupId>com.alibaba.cloud</groupId> 
  3.   <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> 
  4. </dependency> 

 

對于 spring-cloud-alibaba 相關(guān)的版本依賴信息如下:

  1. <properties> 
  2.   <spring-boot.version>2.3.10.RELEASE</spring-boot.version> 
  3.   <spring-cloud.version>Hoxton.SR8</spring-cloud.version> 
  4.   <spring-cloud-alibaba.version>2.2.5.RELEASE</spring-cloud-alibaba.version> 
  5. </properties> 
  6. <dependencyManagement> 
  7.   <dependencies> 
  8.     <dependency> 
  9.       <groupId>org.springframework.boot</groupId> 
  10.       <artifactId>spring-boot-dependencies</artifactId> 
  11.       <version>${spring-boot.version}</version> 
  12.       <type>pom</type> 
  13.       <scope>import</scope> 
  14.     </dependency> 
  15.     <dependency> 
  16.       <groupId>org.springframework.cloud</groupId> 
  17.       <artifactId>spring-cloud-dependencies</artifactId> 
  18.       <version>${spring-cloud.version}</version> 
  19.       <type>pom</type> 
  20.       <scope>import</scope> 
  21.     </dependency> 
  22.      
  23.     <dependency> 
  24.       <groupId>com.alibaba.cloud</groupId> 
  25.       <artifactId>spring-cloud-alibaba-dependencies</artifactId> 
  26.       <version>${spring-cloud-alibaba.version}</version> 
  27.       <type>pom</type> 
  28.       <scope>import</scope> 
  29.     </dependency> 
  30.   </dependencies> 
  31. </dependencyManagement> 

 

 

 

2. YML 配置

我們在業(yè)務(wù)服務(wù)中導(dǎo)入了依賴過后,我們需要修改 application.yml 文件讓服務(wù)啟動過后自動注冊到 sentinel-dashboard 服務(wù)上。

  1. spring: 
  2.   cloud: 
  3.     sentinel: 
  4.       transport: 
  5.         port: 8719 
  6.         dashboard: localhost:8080 

3. 測試接口定義

首先我們需要定義對外開放的接口。

  1. @RestController 
  2. public class HelloController { 
  3.      
  4.     @GetMapping("/hello"
  5.     public String hello () { 
  6.         return "OK"
  7.     } 

4. 通過控制臺配置流控規(guī)則

注意:如果已經(jīng)啟動 snetinel-dashboard 后并且啟動業(yè)務(wù)服務(wù),在 sentinel-dashboard 后臺還是沒有服務(wù)的話,我們可以先訪問一下業(yè)務(wù)服務(wù)的接口,然后在刷新snetinel-dashboard 觀察是否正常。如果還是不正常請考慮 sentinel 的 client 版本和 dashboard 是否匹配。

首先選擇自己對應(yīng)服務(wù)展開,然后選擇【簇點鏈路】 菜單。選擇需要流控的接口 /hello 然后選擇 【流控】按鈕進行流控配置

我們可以配置, 我們選擇【閥值類型】選擇【QPS】,然后設(shè)置【單機閥值】 填入 1 。表示該接口每秒鐘只能接受一個 QPS ,如果超過閾值過后就會觸發(fā) 【流控】默認 Sentinel 返回 Blocked by Sentinel (flow limiting)

5. 流控規(guī)則觸發(fā)

如果我們需要觸發(fā)流控規(guī)則我們頻繁訪問 /hello 接口即可。

 

  1. ~ curl http://127.0.0.1:8066/hello 
  2. OK%                                                                                                                                                   ~ curl http://127.0.0.1:8066/hello 
  3. ~ curl http://127.0.0.1:8066/hello 
  4. Blocked by Sentinel (flow limiting)% 

通過上面的結(jié)果我們可以看到當(dāng)單位時間內(nèi)超過閾值過后, 就會觸發(fā) flow limit

整合 RestTemplate

1. YML 配置

Sentinel 整合 Resttemplate 除了需要導(dǎo)入 spring-cloud-starter-alibaba-sentinel 開需要開啟 Sentinel 對 Resttemplate 的支持。

  1. resttemplate: 
  2.   sentinel: 
  3.     enabled: true 

2. 創(chuàng)建 RestTemplate

如果 RestTemplate 在使用的時候需要使用到 Sentinel 的流控規(guī)則,首先需要在創(chuàng)建 RestTemplate 的時候添加 @SentinelRestTemplate 注解。注意: SentinelExceptionHandler 中的方法都是 static 方法

  1. @Configuration 
  2. public class RestTemplateConfig { 
  3.     @Bean 
  4.     @ConditionalOnMissingBean(RestTemplate.class) 
  5.     @LoadBalanced 
  6.     @SentinelRestTemplate( 
  7.             blockHandler = "handlerException", blockHandlerClass = SentinelExceptionHandler.class, 
  8.             fallback = "handleFallback", fallbackClass = SentinelExceptionHandler.class) 
  9.     public RestTemplate restTemplate() { 
  10.         return new RestTemplate(); 
  11.     } 
  12. // 異常處理類 
  13. public class SentinelExceptionHandler { 
  14.      
  15.     //限流熔斷業(yè)務(wù)邏輯 
  16.     public static SentinelClientHttpResponse handlerException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) { 
  17.         String message = JSON.toJSONString(CommonResult.error(-100,"系統(tǒng)錯誤 (限流熔斷業(yè)務(wù)邏輯)")); 
  18.         return new SentinelClientHttpResponse(message); 
  19.     } 
  20.     //異常降級業(yè)務(wù)邏輯 
  21.     public static SentinelClientHttpResponse handleFallback(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) { 
  22.         String message = JSON.toJSONString(CommonResult.error(-100,"系統(tǒng)錯誤 (異常降級業(yè)務(wù)邏輯)")); 
  23.         return new SentinelClientHttpResponse(message); 
  24.     } 

3. 接口定義

下面就是我們使用的代碼,可能寫得稍微有點復(fù)雜,我來解釋一下。首先我是通過 RestTemplate 訪問 stock-service 服務(wù)的 /getStockDetail 接口然后將接口的返回數(shù)據(jù)解析,通過CommonResult 實例對象進行接收, 如果失敗就返回錯誤信息。

  1. @Autowired 
  2. private RestTemplate restTemplate; 
  3. @GetMapping("/hello2"
  4. public CommonResult<OrderModel> hello2() { 
  5.   ParameterizedTypeReference<CommonResult<StockModel>> typeRef = 
  6.     new ParameterizedTypeReference<CommonResult<StockModel>>() { 
  7.   }; 
  8.   ResponseEntity<CommonResult<StockModel>> 
  9.     forEntity = restTemplate.exchange("http://stock-service/getStockDetail", HttpMethod.GET, 
  10.                                       HttpEntity.EMPTY, typeRef); 
  11.   OrderModel orderModel = new OrderModel(); 
  12.   orderModel.setId(100); 
  13.   orderModel.setCode("100-100"); 
  14.   if (Objects.equals(forEntity.getStatusCode(), HttpStatus.OK) && Objects.nonNull(forEntity.getBody())) { 
  15.     CommonResult<StockModel> result = forEntity.getBody(); 
  16.     if (result.getCode() != 1) { 
  17.       return CommonResult.error(null, result.getCode(), result.getMessage()); 
  18.     } 
  19.     orderModel.setStockModel(result.getData()); 
  20.   } 
  21.   return CommonResult.success(orderModel); 

4. 流控觸發(fā)

如果我們頻繁的訪問我們的接口 /hello2 就會出現(xiàn)限流的邏輯

~ curl http://127.0.0.1:8066/hello2

{"code":1,"message":"this is a success message","data":{"id":100,"code":"100-100","stockModel":{"id":1,"code":"STOCK==>1000"}}}

~ curl http://127.0.0.1:8066/hello2

{"code":-100,"message":"系統(tǒng)錯誤 (限流熔斷業(yè)務(wù)邏輯)","data":null}

整合 OpenFegin

1. 導(dǎo)入 openfeign 依賴

Sentinel 整合 Openfeign 需要導(dǎo)入 spring-cloud-starter-openfeign

  1. <dependency> 
  2.   <groupId>org.springframework.cloud</groupId> 
  3.   <artifactId>spring-cloud-starter-openfeign</artifactId> 
  4. </dependency> 

 

2. YML 配置

Sentinel 整合 Openfeign 需要開啟對 feign 的支持,配置如下:

  1. feign: 
  2.   sentinel: 
  3.     enabled: true 

注意:啟動類上要增加 @EnableFeignClients 來配置 Openfeign 的啟用

3. 調(diào)用代碼

Feign 接口調(diào)服務(wù) stock-service 的 /getStockDetail 接口,如果觸發(fā)流控規(guī)則就會執(zhí)行 FallbackFactory 中返回 StockFeign 的本地存根方法。

  1. @FeignClient(name = "stock-service", fallbackFactory = StockFeignFallbackFactory.class) 
  2. public interface StockFeign { 
  3.     @GetMapping("/getStockDetail"
  4.     CommonResult<StockModel> getStockDetail(); 

StockFeignFallbackFactory 類是服務(wù)降級的處理。

  1. @Component 
  2. public class StockFeignFallbackFactory implements FallbackFactory<StockFeign> { 
  3.     private Logger log = LoggerFactory.getLogger(StockFeignFallbackFactory.class); 
  4.     @Override 
  5.     public StockFeign create(Throwable throwable) { 
  6.         return new StockFeign() { 
  7.             @Override 
  8.             public CommonResult<StockModel> getStockDetail() { 
  9.                 log.error("調(diào)用查詢庫存詳情降級", throwable); 
  10.                 return CommonResult.error(null, -100, "調(diào)用查詢庫存詳情降級"); 
  11.             } 
  12.         }; 
  13.     } 

Controller 調(diào)用代碼

  1. @Autowired 
  2. private StockFeign stockFeign; 
  3. @GetMapping("/hello1"
  4. public CommonResult<OrderModel> hello() { 
  5.   CommonResult<StockModel> result = stockFeign.getStockDetail(); 
  6.   if (result.getCode() != 1) { 
  7.     return CommonResult.error(null, result.getCode(), result.getMessage()); 
  8.   } 
  9.   StockModel stockDetail = result.getData(); 
  10.   OrderModel orderModel = new OrderModel(); 
  11.   orderModel.setStockModel(stockDetail); 
  12.   return CommonResult.success(orderModel); 

4. 業(yè)務(wù)執(zhí)行

如果我們多次訪問,Sentinel 就會觸發(fā)降級策略。然后執(zhí)行 StockFeignFallbackFactory 的本地存根方法返回

源碼地址

gitee: https://gitee.com/zhengsh/excavator

參考

https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/en-us/index.html#_spring_cloud_alibaba_sentinel

https://segmentfault.com/a/1190000019070557

 

責(zé)任編輯:武曉燕 來源: 運維開發(fā)故事
相關(guān)推薦

2024-11-05 15:02:41

2024-12-25 15:44:15

2021-05-21 08:30:26

Sentinel GateWay 微服務(wù)

2022-05-09 07:35:48

動態(tài)集群限流

2022-05-29 21:38:11

限流熔斷流量

2024-02-04 10:08:34

2022-05-03 19:38:15

限流微服務(wù)Sentinel

2025-04-08 09:20:00

Sentinel限流微服務(wù)

2023-09-18 14:39:02

2024-09-06 13:53:28

2021-03-16 08:31:59

微服務(wù)Sentinel雪崩效應(yīng)

2021-03-30 10:46:42

SpringBoot計數(shù)器漏桶算法

2020-08-03 08:04:04

限流算法Sentinel

2021-03-22 08:06:59

SpringBootSentinel項目

2019-07-09 12:30:50

開源技術(shù) 軟件

2024-06-14 09:30:58

2023-04-26 09:16:17

2021-11-04 10:11:02

Sentinel網(wǎng)關(guān)限流

2024-09-09 11:35:35

2024-10-16 20:31:25

點贊
收藏

51CTO技術(shù)棧公眾號