Spring Cloud Alibaba 安装
Spring Cloud Alibaba 组件
Nacos:注册中心 & 配置中心
Sentienl:流量控制 & 服务熔断、降级
Seata:分布式事务
Nacos
Nacos 的全称是 Dynamic Naming and Configuration Service,Na 为 naming/nameServer 即注册中心,co 为 configuration 即注册中心,service 是指该注册/配置中心都是以服务为核心。
Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。
官方网址:https://nacos.io/zh-cn/。
安装
安装包下载地址:https://github.com/alibaba/nacos/releases
解压后会有两个重要的文件夹:
bin:运行脚本
conf:配置文件
主要的安装是配置文件修改:
端口修改
Nacos 的默认端口是 8848,如果要修改,前往 conf/application.properties(如果没有则复制一份 application.properties.example 文件,改名即可) 修改,找到 server.port=8848 进行修改。
数据库修改
如果将 Nacos 里的配置进行持久化,则配置 MySQL,将配置存到 MySQL。
在 config 找到 nacos-mysql.sql 文件,在 MySQL 先创建 nacos_config 数据库,然后执行该 sql 文件,在 nacos_config 数据库生成 Nacos 需要的表。
最后打开 conf/application.properties,替换为如下配置:
spring.sql.init.platform=mysql
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://172.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=5000&socketTimeout=8000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=1234如果实现数据库高可用,则可以配置多个数据库,需要修改 db.num 和添加多个数据库源。
spring.sql.init.platform=mysql
### Count of DB:
db.num=2
### Connect URL of DB:
db.url.0=jdbc:mysql://172.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=5000&socketTimeout=8000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=Arthur10035@202207
db.url.1=jdbc:mysql://172.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=5000&socketTimeout=8000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.1=root
db.password.1=1234多数据库源通过 .0,.1 来区分,如果需要更多数据库,依次类推。
单机
Nacos 默认是集群启动方式。如果是单机(一台 Nacos)运行,则需要修改启动方式,编辑 bin/startup.cmd(Windows)或者 /bin/startup.sh(Linux)。
如果是 Windows,则找到
set MODE="cluster"修改为:
set MODE="standalone"然后双击修改后的该文件启动即可。
如果是 Linux,则找到
export MODE="cluster"修改为:
export MODE="standalone"集群
Nacos 默认是集群启动方式,所以无需修改启动方式,而是配置多个集群地址即可。打开 conf/cluster.conf(如果没有则复制一份 cluster.conf.example 文件,改名即可),添加自己的地址和其他 Nacos 的地址(其他 Nacos 也要打开自己的该文件,配置双方 Nacos 地址,实现双向奔赴)。
172.16.49.42:8848 # 自己的地址
172.16.49.46:8848 # 其他 Nacos 的地址最后运行脚本 startup.cmd 或者 startup.sh 即可。
如果默认端口、本地运行,则访问 http://localhost:8848/nacos 进入控制台页面。
客户端配置
安装依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>一个 Nacos 的配置中心使用,一个是 Nacos 的服务注册使用。
application.yml 配置 Nacos 配置中心和服务注册的地址:
spring:
application:
name: generic-service # 项目名
profiles:
active: dev # 运行环境
cloud:
nacos:
config: # 配置中心
server-addr: 172.16.138.184:8848 # Nacos 地址
file-extension: yaml # 文件后缀名
namespace: 5014d494-958a-4476-9aad-880c2a0c9498 # 命名空间 ID
group: DEFAULT_GROUP # 读取文件所在的组
discovery: # 服务注册
service: ${spring.application.name} # 使用微服务的名称作为注册的服务名称
server-addr: 172.16.138.184:8848 # Nacos服务地址
namespace: 5014d494-958a-4476-9aad-880c2a0c9498 # 命名空间 ID
group: DEFAULT_GROUP # 读取文件所在的组
config: # 指定该项目读取配置中心的文件名
import:
- optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
- optional:nacos:${spring.application.name}.${spring.cloud.nacos.config.file-extension}
- optional:nacos:nacos-discovery.yaml?group=DEFAULT_GROUP&refreshEnabled=true
- nacos:datasource.yaml?group=DEFAULT_GROUP&refreshEnabled=true其中 optional 表示可选,即当无法在配置中心读取到该配置文件,也是可以运行项目,如上面标识 datasource.yaml 文件必须要读取到,否则项目启动报错。
Sentinel
概述
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。
Sentinel 是由阿里巴巴中间件团队开发的开源项目,是一种面向分布式微服务架构的轻量级高可用流量控制组件
Sentinel 主要以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度帮助用户保护服务的稳定性。
Sentinel 具有以下特征:
丰富的应用场景:Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等
完备的实时监控:Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况
广泛的开源生态:Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Apache Dubbo、gRPC、Quarkus 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。同时 Sentinel 提供 Java/Go/C++ 等多语言的原生实现
完善的 SPI 扩展机制:Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑。例如定制规则管理、适配动态数据源等
Sentinel 基本概念
资源
资源是 Sentinel 的关键概念。它可以是 Java 应用程序中的任何内容,例如,由应用程序提供的服务,或由应用程序调用的其它应用提供的服务,甚至可以是一段代码。在接下来的文档中,我们都会用资源来描述代码块。
只要通过 Sentinel API 定义的代码,就是资源,能够被 Sentinel 保护起来。大部分情况下,可以使用方法签名,URL,甚至服务名称作为资源名来标示资源。
规则
围绕资源的实时状态设定的规则,可以包括流量控制规则、熔断降级规则以及系统保护规则。所有规则可以动态实时调整。
Sentinel 的组成
Sentinel 主要由以下两个部分组成:
Sentinel 核心库:Sentinel 的核心库不依赖任何框架或库,能够运行于 Java 8 及以上的版本的运行时环境中,同时对 Spring Cloud、Dubbo 等微服务框架提供了很好的支持
Sentinel 控制台(Dashboard):Sentinel 提供的一个轻量级的开源控制台,它为用户提供了机器自发现、簇点链路自发现、监控、规则配置等功能
Sentinel 核心库不依赖 Sentinel Dashboard,但两者结合使用可以有效的提高效率,让 Sentinel 发挥它最大的作用。
安装控制台
Sentinel 提供了一个轻量级的开源控制台 Sentinel Dashboard,它提供了机器发现与健康情况管理、监控(单机和集群)、规则管理与推送等多种功能。
Sentinel 控制台提供的功能如下:
查看机器列表以及健康情况:Sentinel 控制台能够收集 Sentinel 客户端发送的心跳包,判断机器是否在线
监控(单机和集群聚合):Sentinel 控制台通过 Sentinel 客户端暴露的监控 API,可以实现秒级的实时监控
规则管理和推送:通过 Sentinel 控制台,我们还能够针对资源定义和推送规则
鉴权:从 Sentinel 1.6.0 起,Sentinel 控制台引入基本的登录功能,默认用户名和密码都是 sentinel
Sentinel Dashboard 是我们配置和管理规则(例如流控规则、熔断降级规则等)的重要入口之一。通过它,我们不仅可以对规则进行配置和管理,还能实时查看规则的效果。
启动:(全部使用默认配置)
java -jar sentinel-dashboard-1.8.6.jar启动时指定端口:
java -Dserver.port=8480 -jar sentinel-dashboard-1.8.6.jar启动时指定端口,是否监控自己,项目名称,登录的帐号和密码:
java -Dserver.port=8480 -Dcsp.sentinel.dashboard.server=localhost:8480 -Dproject.name=sentinel-dashboard -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboard.auth.password=123456 -jar sentinel-dashboard-1.8.6.jar参数说明:(注意:参数要放到 -jar 的前边)
# 指定控制台的端口为8480
-Dserver.port=8480
# 指定要被哪个控制台监控(这里指定的是自己监控自己)
-Dcsp.sentinel.dashboard.server=localhost:8480
# 指定实例名称(名称会在控制台左侧以菜单显示)
-Dproject.name=sentinel-dashboard
# 设置登录的帐号为:sentinel
-Dsentinel.dashboard.auth.username=sentinel
# 设置登录的密码为:123456
-Dsentinel.dashboard.auth.password=123456客户端配置
引入依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- Sentinel Nacos 持久化依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>第一个是 Sentinel 的使用,第二个是 Sentinel 读取在 Nacos 的配置。
application.yml 配置 Sentienl 的地址:
spring:
application:
name: generic-service # 项目名
profiles:
active: dev # 运行环境
cloud:
sentinel:
transport:
dashboard: 172.16.138.184:8080 # 控制台地址
web-context-unify: false
datasource: # 读取在 Nacos 的配置(持久化)
generic-service: # 随便取,这里以项目名命名
nacos:
server-addr: 172.16.138.184:8848 # nacos地址
namespace: 5014d494-958a-4476-9aad-880c2a0c9498 # 命名空间 ID
dataId: ${spring.application.name}-flow-rules # 文件名
groupId: DEFAULT_GROUP # 文件所在的分组
dataType: json # 文件是 JSON 格式
ruleType: flow # 规则类型
username: nacos # Nacos 用户名
password: nacos # Nacos 密码此时在 Sentinel 可以读取 Nacos 的配置,但是无法在 Sentinel 添加规则配置时,同步到 Nacos。
换句话说,就是我们目前只能在 Nacos 手动添加 Sentienl 需要的规则配置,然后 Sentienl 去读取,而无法我们在操作 Sentienl 的规则时,这些规则自动同步到 Nacos。也就是 Nacos 单向奔赴。
如果 Sentinel 的规则配置自动同步到 Nacos,需要更改源码,即下载 Sentinel Dashboard 的代码进行更改,然后打包成新的 jar。具体自行百度,或者参考如下链接:https://blog.csdn.net/weixin_53041251/article/details/129651977。
自定义异常处理器
当 Sentinel 里面发生限流降级,授权拦截等等各种异常时,它都会抛出 BlockException。
因此自定义一个类实现 BlockExceptionHandler 接口后,当 Sentinel 抛出内部异常时,将会触发该实现类。
这个方法有三个参数:
- HttpServletRequest request:request 对象
- HttpServletResponse response:response 对象
- BlockExceptione:被 Sentinel 拦截时抛出的异常
其中 BlockException 包含多个不同的子类:
| 异常 | 说明 |
|---|---|
| FlowException | 限流异常 |
| ParamFlowException | 热点参数限流的异常 |
| DegradeException | 降级异常 |
| AuthorityException | 授权规则异常 |
| SystemBlockException | 系统规则异常 |
因此我们就可以对异常类型做个判断,判断是这 5 种中的哪一种,从而去返回不同的结果,做不同处理。
public class SentinelExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String s, BlockException e) throws Exception {
String message = "未知异常";
int status = 429;
if (e instanceof FlowException) {
message = "请求被限流了";
} else if (e instanceof ParamFlowException) {
message = "请求被热点参数限流";
} else if (e instanceof DegradeException) {
message = "请求被降级了";
} else if (e instanceof AuthorityException) {
message = "没有权限访问";
status = 401;
}
long epochMilli = Instant.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
renderString(response, "{\"code\": " + 200 + ", \"message\": " + message + ", \"status\": \"success\", \"data\": null, \"timeStamp\": " + epochMilli + "}", status);
}
/**
* 将字符串渲染到客户端
*
* @param response 渲染对象
* @param jsonMsg 待渲染的字符串
* @param status 状态码
*/
public void renderString(HttpServletResponse response, String jsonMsg, Integer status) {
try {
response.setStatus(status);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonMsg);
} catch (IOException e) {
log.error(e.getMessage());
}
}
}授权规则
Sentinel 有限流、熔断、热线、系统、授权规则。其中大部分都可以在控制台进行配置。
授权规则比较特殊
Seata
Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。
对业务无侵入:即减少技术架构上的微服务化所带来的分布式事务问题对业务的侵入
高性能:减少分布式事务解决方案所带来的性能消耗
官方文档:https://seata.io/zh-cn/index.html。
seata 的几种术语:
TC(Transaction Coordinator):事务协调者。管理全局的分支事务的状态,用于全局性事务的提交和回滚
TM(Transaction Manager):事务管理者。用于开启、提交或回滚事务
RM(Resource Manager):资源管理器。用于分支事务上的资源管理,向 TC 注册分支事务,上报分支事务的状态,接收 TC 的命令来提交或者回滚分支事务
安装
下载地址:http://seata.io/zh-cn/blog/download.html。
接着解压下载的压缩包。
数据库创建
在 MySQL 创建 Seata 需要的务日志,回滚日志等表。
先在 MySQL,创建 seata 数据库,然后打开 script\server\db,在 MySQL 运行 mysql.sql,最后可以看到 seata 数据库下有 Seata 需要的表。
此时 Seata 还没有和 seata 数据库绑定,下面配置文件修改将进行绑定。
配置文件修改
这里将修改 Seata 的一些配置:
绑定 Nacos,从 Nacos 读取需要的配置文件
注册 Nacos,将 Seata 服务注册到 Nacos
持久化 MySQL,Seata 执行过程的事务日志,回滚日志存储到 MySQL
打开 conf/application.yml 文件,将 config、registry 改为 Nacos,store 先去掉,后面 store 的配置将放在 Nacos 里:
server:
port: 7091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${log.home:${user.home}/logs/seata}
console:
user:
username: seata
password: seata
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
server-addr: 192.168.1.5:8848
namespace: acf53419-d42c-4041-b97a-166ce915d92e
group: DEFAULT_GROUP
username: nacos
password: nacos
data-id: seata-server.properties # 配置文件名
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
server-addr: ${seata.config.nacos.server-addr}
application: ${spring.application.name}
namespace: ${seata.config.nacos.namespace}
group: ${seata.config.nacos.group}
username: ${seata.config.nacos.username}
password: ${seata.config.nacos.password}
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
csrf-ignore-urls: /metadata/v1/**
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.jpeg,/**/*.ico,/api/v1/auth/login,/version.json,/health,/error,/vgroup/v1/**如果需要更多的配置参考,请打开 application.example.yml 参考。
配置同步到 Nacos
我们需要实现准备 Seata 需要的配置文件,将其放到 Nacos,这样启动的时候 Seata 就能读取到。
手动同步
在 Nacos 新建一个配置,名字叫做 seataServer.properties,这个名字对应上面 Seata 项目的 application.yml 的 seata.config.nacos.data-id。如果想转换为 yaml,则在 Nacos 配置名和项目 application.yml 同时更改。
然后将 script/config-center/config.txt 的内容复制过来,其中如果没用到 Redis 和 file,都可以删除,然后三个 store.mode 都改成 db,接着修改 MySQL 的数据库源
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableTmClientBatchSendRequest=false
transport.enableRmClientBatchSendRequest=true
transport.enableTcServerBatchSendResponse=false
transport.rpcRmRequestTimeout=30000
transport.rpcTmRequestTimeout=30000
transport.rpcTcRequestTimeout=30000
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
transport.serialization=seata
transport.compressor=none
#Transaction routing rules configuration, only for the client
service.vgroupMapping.default_tx_group=default
#If you use a registry, you can ignore it
service.default.grouplist=127.0.0.1:8091
service.disableGlobalTransaction=false
client.metadataMaxAgeMs=30000
#Transaction rule configuration, only for the client
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=true
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.rm.sagaJsonParser=fastjson
client.rm.tccActionInterceptorOrder=-2147482648
client.rm.sqlParserType=druid
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
client.tm.interceptorOrder=-2147482648
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
#For TCC transaction mode
tcc.fence.logTableName=tcc_fence_log
tcc.fence.cleanPeriod=1h
# You can choose from the following options: fastjson, jackson, gson
tcc.contextJsonParserType=fastjson
#Log rule configuration, for client and server
log.exceptionRate=100
#Transaction storage configuration, only for the server. The file, db, and redis configuration values are optional.
store.mode=db
store.lock.mode=db
store.session.mode=db
#Used for password encryption
store.publicKey=
#If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
#These configurations are required if the `store mode` is `db`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `db`, you can remove the configuration block.
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=username
store.db.password=password
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.vgroupTable=vgroup-table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
#These configurations are required if the `store mode` is `redis`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `redis`, you can remove the configuration block.
store.redis.mode=single
store.redis.type=pipeline
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
store.redis.sentinel.masterName=
store.redis.sentinel.sentinelHosts=
store.redis.sentinel.sentinelPassword=
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.password=
store.redis.queryLimit=100
#Transaction rule configuration, only for the server
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
server.distributedLockExpireTime=10000
server.session.branchAsyncQueueSize=5000
server.session.enableBranchAsyncRemove=false
server.enableParallelRequestHandle=true
server.enableParallelHandleBranch=false
server.applicationDataLimit=64000
server.applicationDataLimitCheck=false
server.raft.server-addr=127.0.0.1:7091,127.0.0.1:7092,127.0.0.1:7093
server.raft.snapshotInterval=600
server.raft.applyBatch=32
server.raft.maxAppendBufferSize=262144
server.raft.maxReplicatorInflightMsgs=256
server.raft.disruptorBufferSize=16384
server.raft.electionTimeoutMs=2000
server.raft.reporterEnabled=false
server.raft.reporterInitialDelay=60
server.raft.serialization=jackson
server.raft.compressor=none
server.raft.sync=true
#Metrics configuration, only for the server
metrics.enabled=true
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898脚本同步
除了手动同步,我们可以采用脚本来进行同步,同步到 Nacos 后,不会是一个配置文件,而是多个配置文件,每个配置文件就是 key,内容是 Value。比如上面 seataServer.properties 的 transport.type 作为 data-id,内容为 TCP。
接着打开 script/config-center/nacos,运行 nacos-config.sh,将剩下的其他配置文件推到 Nacos。
如果在 Windows,需要打开 Git-Bash 运行。
nacos-config.sh -h 172.16.138.184 -p 8848 -t 08e8c083-a242-4407-94bb-16a096b41d5d -u nacos -w nacosh 是 Nacos 的地址
p 是 Nacos 的端口
t 是 Nacos 的命名空间 ID
u 是 Nacos 用户名
w 是 Nacos 密码
添加数据库驱动
Seata 2.2.0 版本后,已经去掉了数据库的驱动 jar 包,所以需要手动往 seata-server\lib\jdbc 里添加数据库驱动,如 MySQL 的驱动,否则直接启动 seaata 会报错无法找到数据库驱动。
启动
双击 bin/seata-server.bat(Windows)或者 bin/seata-server.sh(Linux)文件启动。
客户端配置(RM)
添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>保持 seata-spring-boot-starter 版本和自己的 seata-server.jar 版本一致
application.yml 配置
seata:
enabled: true
config:
type: nacos
nacos:
server-addr: 172.16.138.184:8848
data-id: seataServer.properties
group: SEATA_GROUP
namespace: 08e8c083-a242-4407-94bb-16a096b41d5d
username: nacos
password: nacos
registry:
type: nacos
nacos:
server-addr: 172.16.138.184:8848
group: SEATA_GROUP
namespace: 08e8c083-a242-4407-94bb-16a096b41d5d
username: nacos
password: nacos
application: seata-server
cluster: default
tx-service-group: default_tx_group # 事务分组配置注意的是:seata.tx-service-group 的值是 default_tx_group,对应着 Nacos 的 seataServer.properties 里的
service.vgroupMapping.default_tx_group=default这个规范是 seata.service.vgroup-mapping.事务分组名=集群名称,因为我们有很多客户端,所以我们要配置一个事务分组,即在 application.yml 里的 default_tx_group 就对应 Nacos seataServer.properties 的 default_tx_group。
而 default 就是集群名称,也就是 Nacos 的集群名称,默认是 default。
如果修改了 Nacos 的集群名称,则 default 要进行修改。
当然也可以在 application.yml 写如下内容,该内容覆盖 Nacos seataServer.properties 上的内容:
seata:
service:
vgroup-mapping:
default_tx_group: default # 指定事务分组至集群映射关系(等号右侧的集群名需要与 Seata-server 注册到 Nacos 的 cluster 保持一致)使用
AT 模式
在需要开启事务的方法上加 @GlobalTransactional。