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.mzph.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。我们还会探讨在安…