第4章 Docker应用实战-Docker部署Seata
作者:王珂
邮箱:49186456@qq.com
大家好,我是王珂老师,一个在IT行业摸爬滚打十多年的老兵。讲实战,重应用是我讲课唯一的追求。如果你感觉我讲的还不错,那么请点赞、收藏加关注,并转发给你身边的小伙伴,录视频不易,希望得到你支持与认可。
今天给大家带来一套云原生课程,将从零开始,手把手教你搭建一套企业级云原生环境。通过本套课程,可以让你避开坑、少踩雷,快速上手,将案例直接移植到实际项目。
Seata软件包下载,需要下载两个软件包
seata-1.7.1.zip
https://github.com/seata/seata/archive/v1.7.1.zip
seata-server-1.7.1.tar.gz
https://github.com/seata/seata/releases/download/v1.7.1/seata-server-1.7.1.zip
Seata Server数据库
1)创建数据库
CREATE DATABASE IF NOT EXISTS seata_server CHARACTER SET utf8 COLLATE utf8_general_ci;
2)运行初始化脚本
seata数据库的初始化脚本位于:
seata-server-1.7.1\seata\script\server\db\mysql.sql
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-1.7.1\script\client
该目录下
at\db\mysql.sql 存放AT模式对应的建表脚本
-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
`branch_id` BIGINT NOT NULL COMMENT 'branch transaction id',
`xid` VARCHAR(128) NOT NULL COMMENT 'global transaction id',
`context` VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
`rollback_info` LONGBLOB NOT NULL COMMENT 'rollback info',
`log_status` INT(11) NOT NULL COMMENT '0:normal status,1:defense status',
`log_created` DATETIME(6) NOT NULL COMMENT 'create datetime',
`log_modified` DATETIME(6) NOT NULL COMMENT 'modify datetime',
UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
saga\db 存放SAGA模式对应的建表脚本
我们选择nacos作为seata的注册中心和配置。因此首先需要在nacos中对seata做相应配置。
在nacos创建两个命名空间
命名空间ID | 命名空间名称 | 描述 |
---|---|---|
4b974c46-a7cd-46c3-95ab-e67d0cb121cc | microservice-dev | 微服务开发环境 |
95f1b3fd-2566-4864-8182-09279ba0a779 | seata-dev | seata开发环境 |
在nacos配置中心配置seata的存储模式配置
命名空间:seata-dev
Data ID: seataServer.properties
Group: SEATA_GROUP
配置格式:Properties
store.mode=db
#-----db-----
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://192.168.1.17:3316/seata_server?useUnicode=true&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false
store.db.user=root
store.db.password=123456
# 数据库初始连接数
store.db.minConn=1
# 数据库最大连接数
store.db.maxConn=20
# 获取连接时最大等待时间 默认5000,单位毫秒
store.db.maxWait=5000
# 全局事务表名 默认global_table
store.db.globalTable=global_table
# 分支事务表名 默认branch_table
store.db.branchTable=branch_table
# 全局锁表名 默认lock_table
store.db.lockTable=lock_table
# 查询全局事务一次的最大条数 默认100
store.db.queryLimit=100
我们将docker-compose所有项目文件组织在seata-1.7.1目录中,其目录结构如下:
├ seata-1.7.1
├── seata-server
│ └── resources # 资源文件目录
│ ├── application.example.yml # seata-server配置文件样例
│ ├── application.yml # seata-server的配置文件
│ ├── logback # logback 日志文件目录
│ │ ├── console-appender.xml
│ │ ├── file-appender.xml
│ │ ├── kafka-appender.xml
│ │ └── logstash-appender.xml
│ ├── logback-spring.xml # logback日志配置文件
└── seata-standlone-mysql.yml # docker-compose文件
Seata Server 1.5.0版本开始,配置文件改为application.yml,所以在使用自定义配置的时候,需要先把原生配置拷贝出来
为了获取seata server 1.5.2的配置文件,我们需要先启动一个seata server 1.5.2的服务,然后再从启动的容器实例中把默认的配置文件复制出来,再进行修改。
docker-compose.yaml
version: "3.1"
services:
seata-server:
image: seataio/seata-server:1.5.2
ports:
- "7091:7091"
- "8091:8091"
临时创建seata-server
docker-compose -f ./docker-compose.yaml up -d
容器创建成功后,通过docker cp
命令把容器中/seata-server/resources
位置的资源文件拷贝到宿主机指定位置。 在宿主机指定位置我们就可以看到对应的application.yml
配置文件,相关的配置只需要修改这个文件即可。
docker ps seata-server:/seata-server/resources ./
version: "3.1"
services:
seata-server:
image: seataio/seata-server:1.7.1-slim
ports:
- "7091:7091"
- "8091:8091"
environment:
- STORE_MODE=db
# 以SEATA_IP作为host注册seata server
- SEATA_IP=192.168.1.17
- SEATA_PORT=8091
volumes:
- "/usr/share/zoneinfo/Asia/Shanghai:/etc/localtime" # 设置系统时区
- "/usr/share/zoneinfo/Asia/Shanghai:/etc/timezone" # 设置时区
# 假设我们通过docker cp命令把资源文件拷贝到相对路径`./seata-server/resources`中
- "./seata-server/resources:/seata-server/resources"
资源目录seata-1.7.1\seata-server\resources下的文件
application.yml
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:
config:
type: nacos
nacos:
server-addr: 192.168.1.17:8848
namespace: 95f1b3fd-2566-4864-8182-09279ba0a779
group: SEATA_GROUP
username: nacos
password: nacos
context-path:
##if use MSE Nacos with auth, mutex with username/password attribute
#access-key:
#secret-key:
data-id: seataServer.properties
registry:
type: nacos
nacos:
application: seata-server
server-addr: 192.168.1.17:8848
group: MICROSERVICE_GROUP
namespace: 4b974c46-a7cd-46c3-95ab-e67d0cb121cc
cluster: default
username: nacos
password: nacos
context-path:
##if use MSE Nacos with auth, mutex with username/password attribute
#access-key:
#secret-key:
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
server:
service-port: 8091 #If not configured, the default is '${server.port} + 1000'
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
retry-dead-threshold: 130000
xaer-nota-retry-timeout: 60000
enableParallelRequestHandle: true
recovery:
committing-retry-period: 1000
async-committing-retry-period: 1000
rollbacking-retry-period: 1000
timeout-retry-period: 1000
undo:
log-save-days: 7
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
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
logback-spring.xml
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextListener class="io.seata.server.logging.listener.SystemPropertyLoggerContextListener"/>
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx2" converterClass="io.seata.server.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<springProperty name="PORT" source="server.port" defaultValue="7091"/>
<springProperty name="LOG_BASH_DIR" source="spring.config.additional-location" defaultValue="" />
<springProperty name="APPLICATION_NAME" source="spring.application.name" defaultValue="seata-server"/>
<if condition='property("LOG_BASH_DIR").equals("")'>
<then>
<include resource="logback/console-appender.xml"/>
<include resource="logback/file-appender.xml"/>
then>
<else>
<include file="${LOG_BASH_DIR}/logback/console-appender.xml"/>
<include file="${LOG_BASH_DIR}/logback/file-appender.xml"/>
else>
if>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE_ALL"/>
<appender-ref ref="FILE_WARN"/>
<appender-ref ref="FILE_ERROR"/>
root>
<logger name="org.springframework.security.config.annotation.web.builders.WebSecurity" level="ERROR"/>
<logger name="org.springframework.security.web.DefaultSecurityFilterChain" level="ERROR"/>
configuration>
logback目录
logback包含以下4个appender文件
console-appender.xml
file-appender.xml
kafka-appender.xml
logstash-appender.xml
docker-compose -f ./seata-1.7.1/seata-standlone-mysql.yml up -d
注意:默认内存-Xmx2048m -Xms2048m太大,尚未调整