Spring Cloud Alibaba 架構-Sentinel整合nacos和gateway

官網地址

sentinel官網: https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E9%A1%B5
sentinel 下載地址: https://github.com/alibaba/Sentinel/releases
nacos官網: https://nacos.io/zh-cn/docs/deployment.html
nacos下載地址: https://github.com/alibaba/nacos/releases

部署

容器部署

簡化的示例,展示了如何在Docker Compose文件中定義Sentinel和Nacos:

version: '3'  
services:  nacos:  image: nacos/nacos-server:latest  ports:  - "8848:8848"  environment:  - MODE=standalone  # 其他Nacos配置...  sentinel:  image: your-sentinel-image:latest  # 替換為您的Sentinel鏡像  ports:  - "8080:8080"  # Sentinel控制臺端口  depends_on:  - nacos  environment:  - SPRING_CLOUD_SENTINEL_DATASOURCE_DS1_NAME=nacos  - SPRING_CLOUD_SENTINEL_DATASOURCE_DS1_TYPE=nacos  - SPRING_CLOUD_SENTINEL_DATASOURCE_DS1_NAMESPACE=public  # 您的Nacos命名空間  - SPRING_CLOUD_SENTINEL_DATASOURCE_DS1_SERVER-ADDR=nacos:8848  # 指向Nacos服務的地址  # 其他Sentinel配置...

啟動Docker Compose

docker-compose up -d

jar啟動

  1. 下載Sentinel JAR包
  • 訪問Sentinel的官方GitHub地址或Maven倉庫,下載適合您項目的Sentinel JAR包。例如,sentinel-dashboard-xxx.jar。
  1. 配置Nacos數據源:
  • 在Spring Cloud項目中,需要添加Nacos數據源相關的Maven依賴。例如:
<dependency>  <groupId>com.alibaba.csp</groupId>  <artifactId>sentinel-datasource-nacos</artifactId>  <version>您的Sentinel版本</version>  
</dependency>
  • 在項目的配置文件(如application.properties或application.yml)中,配置Nacos數據源的相關參數,如Nacos服務器的地址、端口、命名空間、數據ID等。例如:
spring.cloud.sentinel.datasource.ds1.nacos.server-addr=127.0.0.1:8848  
spring.cloud.sentinel.datasource.ds1.nacos.dataId=sentinel-rules  
spring.cloud.sentinel.datasource.ds1.nacos.group=DEFAULT_GROUP  
spring.cloud.sentinel.datasource.ds1.nacos.namespace=public  
# 其他配置項...
  1. 啟動Sentinel:
  • 在命令行中,進入包含Sentinel JAR包的目錄。
  • 使用java -jar命令啟動Sentinel,并指定配置文件(如果需要)。例如:
java -jar sentinel-dashboard-xxx.jar --spring.config.location=classpath:application.properties

注意:這里假設已經將Nacos數據源的配置寫入了application.properties文件,并且該文件位于類路徑(classpath)下。如果配置文件位置不同,需要相應地修改–spring.config.location參數的值。

DEMO

官網demo地址:https://github.com/alibaba/Sentinel/blob/master/sentinel-demo/sentinel-demo-nacos-datasource/src/main/java/com/alibaba/csp/sentinel/demo/datasource/nacos/NacosDataSourceDemo.java

public class NacosDataSourceDemo {private static final String KEY = "TestResource";// nacos server ipprivate static final String remoteAddress = "localhost:8848";// nacos groupprivate static final String groupId = "Sentinel_Demo";// nacos dataIdprivate static final String dataId = "com.alibaba.csp.sentinel.demo.flow.rule";// if change to true, should be config NACOS_NAMESPACE_IDprivate static boolean isDemoNamespace = false;// fill your namespace id,if you want to use namespace. for example: 0f5c7314-4983-4022-ad5a-347de1d1057d,you can get it on nacos's consoleprivate static final String NACOS_NAMESPACE_ID = "${namespace}";public static void main(String[] args) {if (isDemoNamespace) {loadMyNamespaceRules();} else {loadRules();}// Assume we config: resource is `TestResource`, initial QPS threshold is 5.FlowQpsRunner runner = new FlowQpsRunner(KEY, 1, 100);runner.simulateTraffic();runner.tick();}private static void loadRules() {ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(remoteAddress, groupId, dataId,source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));FlowRuleManager.register2Property(flowRuleDataSource.getProperty());}private static void loadMyNamespaceRules() {Properties properties = new Properties();properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);properties.put(PropertyKeyConst.NAMESPACE, NACOS_NAMESPACE_ID);ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));FlowRuleManager.register2Property(flowRuleDataSource.getProperty());}}

集成Spring Cloud Gateway

步驟:
1. 添加依賴
在 Spring Cloud Gateway 項目的 pom.xml 文件中,添加 Sentinel 和 Spring Cloud Alibaba 的相關依賴。這通常包括 Spring Cloud Alibaba Sentinel 的依賴以及 Spring Cloud Gateway 的依賴。

<!-- Spring Cloud Gateway 核心 -->  
<dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-gateway</artifactId>  
</dependency>  <!-- Spring Cloud Alibaba Sentinel -->  
<dependency>  <groupId>com.alibaba.cloud</groupId>  <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>  <version>你的版本號</version>  
</dependency>

2. 配置Sentinel
在 application.yml 或 application.properties 配置文件中,配置 Sentinel 的相關參數,如數據源(例如 Nacos)、限流規則、熔斷規則等。

spring:  cloud:  sentinel:  transport:  dashboard: localhost:8080 # Sentinel 控制臺地址  port: 8719 # Sentinel 客戶端與控制臺通信的端口,默認8719  datasource:  # 這里可以配置 Nacos 數據源,用于動態加載限流規則等  flow:  nacos:  server-addr: localhost:8848  dataId: ${spring.application.name}-flow-rules  groupId: DEFAULT_GROUP  namespace: public  rule-type: flow  # 其他 Sentinel 和 Gateway 配置...

3. 設置限流和熔斷規則
可以通過 Sentinel 控制臺動態設置限流和熔斷規則,也可以通過配置文件靜態設置。在 Sentinel 控制臺中,可以創建流控規則、熔斷規則等,并實時查看和修改它們。
4. 啟動于測試
啟動 Spring Cloud Gateway 應用,并通過瀏覽器或 Postman 等工具發送請求來測試限流和熔斷功能是否生效。可以觀察 Sentinel 控制臺中的實時監控數據,以驗證限流和熔斷規則是否按預期工作。

DEMO

官網地址: https://github.com/alibaba/Sentinel/blob/master/sentinel-demo/sentinel-demo-spring-cloud-gateway/pom.xml

@Configuration
public class GatewayConfiguration {private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer) {this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {// Register the block exception handler for Spring Cloud Gateway.return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);}@Bean@Order(-1)public GlobalFilter sentinelGatewayFilter() {return new SentinelGatewayFilter();}@PostConstructpublic void doInit() {initCustomizedApis();initGatewayRules();}private void initCustomizedApis() {Set<ApiDefinition> definitions = new HashSet<>();ApiDefinition api1 = new ApiDefinition("some_customized_api").setPredicateItems(new HashSet<ApiPredicateItem>() {{add(new ApiPathPredicateItem().setPattern("/ahas"));add(new ApiPathPredicateItem().setPattern("/product/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));}});ApiDefinition api2 = new ApiDefinition("another_customized_api").setPredicateItems(new HashSet<ApiPredicateItem>() {{add(new ApiPathPredicateItem().setPattern("/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));}});definitions.add(api1);definitions.add(api2);GatewayApiDefinitionManager.loadApiDefinitions(definitions);}private void initGatewayRules() {Set<GatewayFlowRule> rules = new HashSet<>();rules.add(new GatewayFlowRule("aliyun_route").setCount(10).setIntervalSec(1));rules.add(new GatewayFlowRule("aliyun_route").setCount(2).setIntervalSec(2).setBurst(2).setParamItem(new GatewayParamFlowItem().setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)));rules.add(new GatewayFlowRule("httpbin_route").setCount(10).setIntervalSec(1).setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER).setMaxQueueingTimeoutMs(600).setParamItem(new GatewayParamFlowItem().setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER).setFieldName("X-Sentinel-Flag")));rules.add(new GatewayFlowRule("httpbin_route").setCount(1).setIntervalSec(1).setParamItem(new GatewayParamFlowItem().setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM).setFieldName("pa")));rules.add(new GatewayFlowRule("httpbin_route").setCount(2).setIntervalSec(30).setParamItem(new GatewayParamFlowItem().setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM).setFieldName("type").setPattern("warn").setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)));rules.add(new GatewayFlowRule("some_customized_api").setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME).setCount(5).setIntervalSec(1).setParamItem(new GatewayParamFlowItem().setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM).setFieldName("pn")));GatewayRuleManager.loadRules(rules);}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/16055.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/16055.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/16055.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Shopee單個商品詳情采集

Shopee商品詳情頁數據采集實戰 作為東南亞地區最大的電商平臺之一,Shopee擁有超過3億活躍用戶。對于跨境電商企業、市場分析師等角色而言,從Shopee獲取商品數據是非常有價值的。本文將介紹如何使用Python程序采集Shopee單個商品詳情頁數據。 1. 確定采集目標和技術方案 確定…

路由傳參和獲取參數的三種方式

路由傳參和獲取參數在前端開發中是一個常見的需求&#xff0c;特別是在使用如 Vue.js、React 等前端框架時。下面&#xff0c;我將以 Vue.js 為例&#xff0c;介紹三種常見的路由傳參和獲取參數的方式&#xff1a; 1. 使用 params 傳參 傳參&#xff1a; 在路由配置中&#…

SQL Server 2022 STRING_SPLIT表值函數特性增強

SQL Server 2022 STRING_SPLIT表值函數特性增強 1、本文內容 List item語法參數返回類型注解 適用于&#xff1a;SQL Server 2016 (13.x) 及更高版本Azure SQL 數據庫Azure SQL 托管實例Azure Synapse AnalyticsMicrosoft Fabric 中的 SQL 分析終結點Microsoft Fabric 中的倉…

golang內置包strings和bytes中的Map函數的理解和使用示例

在go的標志內置包strings和bytes中都有一個函數Map, 這個函數的作用是&#xff1a; 將輸入字符串/字節切片中的每個字符使用函數處理后映射后返回一份字符串/字節切片的副本&#xff0c;如果函數中的某個字符返回負數則刪除對應的字符。 作用很簡單&#xff0c;當時對于新手來…

Qt_tftp(未總結)

記錄一下tftp傳輸,日后總結 #ifndef CLIENTWORK_H #define CLIENTWORK_H#include <QObject> #include <QThread>#include <QHostAddress>

關于C的\r回車在不同平臺的問題

首先我們需要搞明白\r和\n是兩回事 \r是回車&#xff0c;前者使光標到行首&#xff0c;&#xff08;carriage return&#xff09; \n是換行&#xff0c;后者使光標下移一格&#xff0c;&#xff08;line feed&#xff09; Linux平臺下 #include <stdio.h> int main()…

Unidac連接Excel文件

終于找到一個連接字符串&#xff0c;記錄一下 UniConnection1.ConnectString : Format(Provider NameODBC;Server"DRIVERMicrosoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb); DBQ%s", [FileName]); UniConnection1.connected:true; UniConnection1.gettable…

神經網絡不確定性綜述(Part I)——A survey of uncertainty in deep neural networks

相關鏈接&#xff1a; 神經網絡不確定性綜述(Part I)——A survey of uncertainty in deep neural networks-CSDN博客 神經網絡不確定性綜述(Part II)——Uncertainty estimation_Single deterministic methods-CSDN博客 神經網絡不確定性綜述(Part III)——Uncertainty est…

Python實現xml解析并輸出到Excel上

1.編寫xml文件 2.使用Python的ElementTree模塊來解析XML import xml.etree.ElementTree as ET from openpyxl import Workbook # 解析XML函數 def parse_xml(xml_file):tree ET.parse(xml_file)root tree.getroot() --打開根節點data []for user in root.findall(Users/Us…

1.手動LogisticRegression模型的訓練和預測

通過這個示例&#xff0c;可以了解邏輯回歸模型的基本原理和訓練過程&#xff0c;同時可以通過修改和優化代碼來進一步探索機器學習模型的訓練和調優方法。 過程: 生成了一個模擬的二分類數據集&#xff1a;通過隨機生成包含兩個特征的數據data_x&#xff0c;并基于一定規則生…

秋招突擊——算法打卡——5/25、5/26——尋找兩個正序數組的中位數

題目描述 自我嘗試 首先&#xff0c;就是兩個有序的數組進行遍歷&#xff0c;遍歷到一半即可。然后求出均值&#xff0c;下述是我的代碼。但這明顯是有問題的&#xff0c;具體錯誤的代碼如下。計算復雜度太高了&#xff0c;O&#xff08;n&#xff09;&#xff0c;所以會超時&…

數據結構--《二叉樹》

二叉樹 1、什么是二叉樹 二叉樹(Binar Tree)是n(n>0)個結點的優先集合&#xff0c;該集合或者為空集(稱為空二叉樹)&#xff0c;或者由一個根結點和兩顆互不相交的、分別稱為根結點的左子樹和右子樹的二叉樹構成。 這里給張圖&#xff0c;能更直觀的感受二叉樹&#xff1…

GDPU JavaWeb mvc模式

搭建一個mvc框架的小實例。 簡易計算器 有一個名為inputNumber.jsp的頁面提供一個表單&#xff0c;用戶可以通過表單輸入兩個數和運算符號提交給Servlet控制器&#xff1b;由名為ComputerBean.java生成的JavaBean負責存儲運算數、運算符號和運算結果&#xff0c;由名為handleCo…

C#中獲取FTP服務器文件

1、從ftp下載pdf的方法 public static void DownloadPdfFileFromFtp(string ftpUrl,string user,string password string localPath) { // 創建FtpWebRequest對象 FtpWebRequest request (FtpWebRequest)WebRequest.Create(ftpUrl); request.Method WebRequestMethods.Ftp…

簡單好用的文本識別方法--付費的好用,免費的更有性價比-記筆記

文章目錄 先說付費的進入真題&#xff0c;免費的來喏&#xff01;PixPin微信 先說付費的 直達網址!!! 進入真題&#xff0c;免費的來喏&#xff01; PixPin 商店里就有 使用示例&#xff1a; 可以看到&#xff1a;貼在桌面上的圖片可以復制圖片中的文字&#xff0c;真的很…

深入了解ASPICE標準:提升汽車軟件開發與質量管理的利器

隨著汽車行業的快速發展和技術創新&#xff0c;汽車軟件的開發和質量管理的重視程度不斷提升。ASPICE&#xff08;Automotive Software Process Improvement and Capability Determination&#xff09;標準作為一種專門針對汽車軟件開發過程的改進和能力評定的框架&#xff0c;…

Springboot+Vue+ElementUI開發前后端分離的員工管理系統01--系統介紹

項目介紹 springboot_vue_emp是一個基于SpringbootVueElementUI實現的前后端分離的員工管理系統 功能涵蓋&#xff1a; 系統管理&#xff1a;用戶管理、角色管理、菜單管理、字典管理、部門管理出勤管理&#xff1a;請假管理、考勤統計、工資發放、工資統計、離職申請、個人資…

8.Redis之hash類型

1.hash類型的基本介紹 哈希表[之前學過的所有數據結構中,最最重要的] 1.日常開發中,出場頻率非常高. 2.面試中,非常重要的考點, Redis 自身已經是鍵值對結構了Redis 自身的鍵值對就是通過 哈希 的方式來組織的 把 key 這一層組織完成之后, 到了 value 這一層~~ value 的其中…

最重要的時間表示,柯橋外貿俄語小班課

в第四格 1、與表示“鐘點”的數詞詞組連用 例&#xff1a; в шесть часов утра 在早上六點 в пять тридцать 在五點半 2、與表示“星期”的名詞連用 例&#xff1a; в пятницу 在周五 в следующий понедельник …

包和依賴管理:Python的pip和conda使用指南

包和依賴管理&#xff1a;Python的pip和conda使用指南 對于Python新手來說&#xff0c;包和依賴管理可能是一個令人困惑的概念。但不用擔心&#xff0c;本文將用淺顯易懂的語言&#xff0c;詳細介紹如何使用Python的兩個主要包管理工具&#xff1a;pip和conda。我們還會探討在安…