目录
- 创建数据库
- 拉取 Seata 镜像
- 挂载目录
- 启动临时容器
- 拷贝临时容器的配置至宿主机
- 完成之后删除临时容器(过河拆桥)
- 自定义配置
- Nacos 配置
- 启动 Seata
- 坑
- 完整 Seata 配置文件(application.yml)
- 完整 Nacos 配置文件(seataServer.properties)
创建数据库
访问 seatax.x.x 获取 mysql.sql 脚本
-- 1. 执行语句创建名为 seata 的数据库
CREATE DATABASE seata DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;
-- 2.执行脚本完成 Seata 表结构的创建
use seata;
-- https://github.com/seata/seata/blob/1.7.1/script/server/db/mysql.sql
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`status` TINYINT NOT NULL,
`application_id` VARCHAR(32),
`transaction_service_group` VARCHAR(32),
`transaction_name` VARCHAR(128),
`timeout` INT,
`begin_time` BIGINT,
`application_data` VARCHAR(2000),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`xid`),
KEY `idx_status_gmt_modified` (`status` , `gmt_modified`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
`branch_id` BIGINT NOT NULL,
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`resource_group_id` VARCHAR(32),
`resource_id` VARCHAR(256),
`branch_type` VARCHAR(8),
`status` TINYINT,
`client_id` VARCHAR(64),
`application_data` VARCHAR(2000),
`gmt_create` DATETIME(6),
`gmt_modified` DATETIME(6),
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(128),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`status` TINYINT NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_status` (`status`),
KEY `idx_branch_id` (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
CREATE TABLE IF NOT EXISTS `distributed_lock`
(
`lock_key` CHAR(20) NOT NULL,
`lock_value` VARCHAR(20) NOT NULL,
`expire` BIGINT,
primary key (`lock_key`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);
拉取 Seata 镜像
执行以下命令拉取 seata 镜像:
docker pull seataio/seata-server:v版本号
docker pull seataio/seata-server:2.0.0
挂载目录
sudo mkdir -p /mydata/seata/config/
启动临时容器
docker run -d -p 8091:8091 -p 7091:7091 --name seata-server seataio/seata-server:2.0.0
拷贝临时容器的配置至宿主机
docker cp seata-server:/seata-server/resources/. /mydata/seata/config/
完成之后删除临时容器(过河拆桥)
docker rm -f seata-server
自定义配置
上面通过自定义配置文件将 Seata 应用的配置拷贝到宿主机的 /mydata/seata/config/
目录下,方便接下来自定义修改配置。
因为配置和注册中心类型选用的是 Nacos ,所以需要调整 /mydata/seata/config/application.yml
配置文件的 seata.config
和seata.registry
两个节点(参考同目录下示例配置application.example.yml
),其他默认无需修改。修改后的配置如下:
192.168.52.131:8848
: 配置中心 Nacos 的 IP 地址
Nacos 配置
命名空间
配置文件
使用 MySQL 作为 Seata 的存储方案,所以需要修改 seataServer.properties
配置文件中的存储模式和数据库连接配置,具体修改如下:
# 配置存储模式为: db(数据库)
store.mode=db
store.lock.mode=db
store.session.mode=db
# 数据库连接配置
store.db.url=jdbc:mysql://192.168.52.131:3306/seata?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
store.db.user=seata
store.db.password=seata
Seata 使用 Nacos 作为配置中心,所以需要将 Seata 配置中心的配置 config.txt 文件导入 Nacos 。
- `192.168.52.131:3306 :MySQL 服务 IP 地址
启动 Seata
执行以下命令来创建并运行 seata 容器
docker run --name seata-server \
--privileged=true \
--restart=always \
-p 8091:8091 \
-p 7091:7091 \
-e STORE_MODE=db \
-v /mydata/seata/config/application.yml:/seata-server/resources/application.yml \
-d seataio/seata-server:2.0.0
docker run --name seata-server \
--privileged=true \
--restart=always \
-p 8091:8091 \
-p 7091:7091 \
-e STORE_MODE=db \
-e SEATA_IP=192.168.52.131 \
-e SEATA_PORT=8091 \
-v /mydata/seata/config:/seata-server/resources \
-d seataio/seata-server:2.0.0
192.168.52.131
: seata-server 所在宿主机的 IP,该IP用于向注册中心注册时使用- 8091 是注册到 nacos 中的服务端端口
- 7091 是其客户端端口
访问 Nacos 控制台,看到 seata-server 已成功注册。
坑
1. Nacos 显示 Seata 服务的 ip 为容器内网 ip 导致微服务无法访问
网上看到以下各种方法均无效
- 使用host网络
- application.yml 指定 spring.cloud.nacos.discovery.ip
以下方法有效 - 容器创建时使用 -e SEATA_IP="宿主机ip"
2. 使用 host 宿主机网络
一开始为了图方便,给 Nacos 用过 host 网络,结果容器程序运行正常,打不开网页,玄学的一批。
也给 Seata 使用 host 网络,为了配置文件里面不用自己手动查询 nacos 和 mysql 的 ip,结果然并卵。
3. seata The distribute lock table is not config, please create the target table and config it
这个是因为很多文档,都只有 3 张表,少了一张。
官方文档说store.db.distributedLockTable
是 1.5.1
版本新增的参数。
https://seata.io/zh-cn/docs/user/configurations
但是很多文档和博客,都只有3张表,第4张在哪里呢?
在这里
https://seata.io/zh-cn/docs/ops/deploy-by-docker-compose.html
里面写到nacos注册中心,db存储
时会提供 [建表脚本]
以及最后最重要的是,要在Nacos配置中心配置seataServer.properties
时,要多加一行
store.db.distributedLockTable=distributed_lock
这点在官网文档都没有提及。
4. 高版本中 BusinessActionContextParameter 和 TwoPhaseBusinessAction 推荐都放在实现类中,接口上的做法后续将会废除
具体参考这个 Issue
2.0.0 TCC模式@BusinessActionContextParameter修饰的参数失效,无法在BusinessActionContext获取
完整 Seata 配置文件(application.yml)
# Copyright 1999-2019 Seata.io Group.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
server:
port: 7091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${log.home:${user.home}/logs/seata}
extend:
logstash-appender:
destination: 127.0.0.1:4560
kafka-appender:
bootstrap-servers: 127.0.0.1:9092
topic: logback_to_logstash
console:
user:
username: seata
password: seata
seata:
# 配置中心-nacos
config:
type: nacos # support: nacos, consul, apollo, zk, etcd3
nacos:
server-addr: 172.17.0.7:8848 #nacos容器内部ip 可通过命名 docker inspect [容器名] 查看ip
namespace: 9e48de1d-9701-4c1d-94cb-8d03edb00531
group: SEATA_GROUP
username: nacos # nacos用户名
password: TMesh729 # nacos密码
context-path: /nacos # 新版nacos默认 /nacos前缀
data-id: seataServer.properties # 配置中心文件名
#if use MSE Nacos with auth, mutex with username/password attribute
#access-key:
#secret-key:
consul:
server-addr: 127.0.0.1:8500
acl-token:
key: seata.properties
apollo:
appId: seata-server
apollo-meta: http://192.168.1.204:8801
apollo-config-service: http://192.168.1.204:8080
namespace: application
apollo-access-key-secret:
cluster: seata
zk:
server-addr: 127.0.0.1:2181
session-timeout: 6000
connect-timeout: 2000
username:
password:
node-path: /seata/seata.properties
etcd3:
server-addr: http://localhost:2379
key: seata.properties
# support: nacos 、 eureka 、 redis 、 zk 、 consul 、 etcd3 、 sofa
# 注册中心-nacos
registry:
type: nacos # support: nacos, eureka, redis, zk, consul, etcd3, sofa
nacos:
application: seata-server
server-addr: 172.17.0.7:8848 #nacos容器内部ip 可通过命名 docker inspect [容器名] 查看ip
group: SEATA_GROUP
namespace: 9e48de1d-9701-4c1d-94cb-8d03edb00531
cluster: default # TC 集群名称,下文 Seata 客户端中配置事务分组名和集群名映射使用
username: nacos # nacos用户名
password: TMesh729 # nacos密码
context-path: /nacos # 新版nacos默认 /nacos前缀
#if use MSE Nacos with auth, mutex with username/password attribute
#access-key:
#secret-key:
eureka:
service-url: http://localhost:8761/eureka
application: default
weight: 1
redis:
server-addr: localhost:6379
db: 0
password:
cluster: default
timeout: 0
zk:
cluster: default
server-addr: 127.0.0.1:2181
session-timeout: 6000
connect-timeout: 2000
username:
password:
consul:
cluster: default
server-addr: 127.0.0.1:8500
acl-token:
etcd3:
cluster: default
server-addr: http://localhost:2379
sofa:
server-addr: 127.0.0.1:9603
application: default
region: DEFAULT_ZONE
datacenter: DefaultDataCenter
cluster: default
group: SEATA_GROUP
address-wait-time: 3000
server:
raft:
group: default
cluster:
snapshot-interval: 600
apply-batch: 32
max-append-bufferSize: 262144
max-replicator-inflight-msgs: 256
disruptor-buffer-size: 16384
election-timeout-ms: 1000
reporter-enabled: false
reporter-initial-delay: 60
serialization: jackson
compressor: none
sync: true # sync log&snapshot to disk
service-port: 8091 #If not configured, the default is '${server.port} + 1000'
# 二阶段提交重试超时时长 单位ms,s,m,h,d,对应毫秒,秒,分,小时,天,默认毫秒。默认值-1表示无限重试
# 公式: timeout>=now-globalTransactionBeginTime,true表示超时则不再重试
# 注: 达到超时时间后将不会做任何重试,有数据不一致风险,除非业务自行可校准数据,否者慎用
max-commit-retry-timeout: -1
# 二阶段回滚重试超时时长
max-rollback-retry-timeout: -1
rollback-retry-timeout-unlock-enable: false
enable-check-auth: true
enable-parallel-request-handle: true
enable-parallel-handle-branch: false
retry-dead-threshold: 130000
xaer-nota-retry-timeout: 60000
enableParallelRequestHandle: true
recovery:
# 二阶段提交未完成状态全局事务重试提交线程间隔时间 默认1000,单位毫秒
committing-retry-period: 1000
# 二阶段异步提交状态重试提交线程间隔时间 默认1000,单位毫秒
async-committing-retry-period: 1000
# 二阶段回滚状态重试回滚线程间隔时间 默认1000,单位毫秒
rollbacking-retry-period: 1000
# 超时状态检测重试线程间隔时间 默认1000,单位毫秒,检测出超时将全局事务置入回滚会话管理器
timeout-retry-period: 1000
undo:
# undo保留天数 默认7天,log_status=1(附录3)和未正常清理的undo
log-save-days: 7
# undo清理线程间隔时间 默认86400000,单位毫秒
log-delete-period: 86400000
session:
branch-async-queue-size: 5000 #branch async remove queue size
enable-branch-async-remove: false #enable to asynchronous remove branchSession
store:
# support: file 、 db 、 redis 、 raft
# 配置存储模式为: db(数据库)
mode: db
session:
mode: db
lock:
mode: db
file:
dir: sessionStore
max-branch-session-size: 16384
max-global-session-size: 512
file-write-buffer-cache-size: 16384
session-reload-read-size: 100
flush-disk-mode: async
db:
datasource: druid
db-type: mysql
# 需要根据mysql的版本调整driverClassName
# mysql8及以上版本对应的driver:com.mysql.cj.jdbc.Driver
# mysql8以下版本的driver:com.mysql.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://172.17.0.2:3306/seata?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
user: seata
password: seata
# 数据库初始连接数
min-conn: 1
# 数据库最大连接数
max-conn: 20
# 全局事务表名 默认global_table
global-table: global_table
# 分支事务表名 默认branch_table
branch-table: branch_table
# 全局锁表名 默认lock_table
lock-table: lock_table
distributed-lock-table: distributed_lock
query-limit: 1000
# 获取连接时最大等待时间 默认5000,单位毫秒
max-wait: 5000
redis:
mode: single
# support: lua 、 pipeline
type: lua
database: 0
min-conn: 10
max-conn: 100
password:
max-total: 100
query-limit: 1000
single:
host: 127.0.0.1
port: 6379
sentinel:
master-name:
sentinel-hosts:
sentinel-password:
metrics:
enabled: false
registry-type: compact
exporter-list: prometheus
exporter-prometheus-port: 9898
transport:
rpc-tc-request-timeout: 15000
enable-tc-server-batch-send-response: false
shutdown:
wait: 3
thread-factory:
boss-thread-prefix: NettyBoss
worker-thread-prefix: NettyServerNIOWorker
boss-thread-size: 1
# security 在 application.yml 中获取
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.jpeg,/**/*.ico,/api/v1/auth/login,/metadata/v1/**
完整 Nacos 配置文件(seataServer.properties)
#For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
#Transport configuration, for client and server
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.enableDegrade=false
service.disableGlobalTransaction=false
#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.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
# undo保留天数 默认7天,log_status=1(附录3)和未正常清理的undo
server.undo.logSaveDays=7
# undo清理线程间隔时间 默认86400000,单位毫秒
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
#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.
# 配置存储模式为: db(数据库)
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
# 需要根据mysql的版本调整driverClassName
# mysql8及以上版本对应的driver:com.mysql.cj.jdbc.Driver
# mysql8以下版本的driver:com.mysql.jdbc.Driver
store.db.driverClassName=com.mysql.cj.jdbc.Driver
# 数据库连接配置
store.db.url=jdbc:mysql://172.17.0.2:3306/seata?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
store.db.user=seata
store.db.password=seata
# 数据库初始连接数
store.db.minConn=1
# 数据库最大连接数
store.db.maxConn=20
# 全局事务表名 默认global_table
store.db.globalTable=global_table
# 分支事务表名 默认branch_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
# 全局锁表名 默认lock_table
store.db.lockTable=lock_table
# 获取连接时最大等待时间 默认5000,单位毫秒
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.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=tmesh729
store.redis.queryLimit=100
#Transaction rule configuration, only for the server
# 二阶段提交未完成状态全局事务重试提交线程间隔时间 默认1000,单位毫秒
server.recovery.committingRetryPeriod=1000
# 二阶段异步提交状态重试提交线程间隔时间 默认1000,单位毫秒
server.recovery.asynCommittingRetryPeriod=1000
# 二阶段回滚状态重试回滚线程间隔时间 默认1000,单位毫秒
server.recovery.rollbackingRetryPeriod=1000
# 超时状态检测重试线程间隔时间 默认1000,单位毫秒,检测出超时将全局事务置入回滚会话管理器
server.recovery.timeoutRetryPeriod=1000
# 二阶段提交重试超时时长 单位ms,s,m,h,d,对应毫秒,秒,分,小时,天,默认毫秒。默认值-1表示无限重试
# 公式: timeout>=now-globalTransactionBeginTime,true表示超时则不再重试
# 注: 达到超时时间后将不会做任何重试,有数据不一致风险,除非业务自行可校准数据,否者慎用
server.maxCommitRetryTimeout=-1
# 二阶段回滚重试超时时长
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
server.distributedLockExpireTime=10000
server.xaerNotaRetryTimeout=60000
server.session.branchAsyncQueueSize=5000
server.session.enableBranchAsyncRemove=false
server.enableParallelRequestHandle=false
#Metrics configuration, only for the server
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
标签:Seata,lock,db,server,client,Docker,安装,store,seata
From: https://www.cnblogs.com/TMesh/p/18676663