docker搭建mysql + nacos + seata

准备环境

服务器
IP : 172.168.10.168
seata官网
seata服务包下载
seata配置下载

mysql

下载镜像
docker pull mysql:8.0.27
创建配置目录、授权
mkdir -p /opt/mysql/{conf,data}

chmod -R 755 /opt/mysql/
mysql配置文件my.cnf
vim /opt/mysql/conf/my.cnf

[mysqld]
pid-file=/var/run/mysqld/mysqld.pid
socket=/var/run/mysqld/mysqld.sock
secure-file-priv= NULL
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
collation_server=utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
# 设置3306端口
port=3306
# 设置mysql的安装目录
basedir=/var/lib/mysql
# 设置mysql数据库的数据的存放目录
datadir=/var/lib/mysql/data
log_error=/var/log/mysql/mysql.log
# 允许最大连接数
max_connections=1000
# 允许连接失败的次数。这是为了防止有人从该主机试图攻击数据库系统
max_connect_errors=100
# 服务端使用的字符集默认为UTF8
character-set-server=utf8mb4
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB
# 默认使用“mysql_native_password”插件认证
default_authentication_plugin=mysql_native_password
#是否对sql语句大小写敏感,1表示不敏感
# lower_case_table_names=1
#MySQL连接闲置超过一定时间后(单位:秒)将会被强行关闭
#MySQL默认的wait_timeout  值为8个小时, interactive_timeout参数需要同时配置才能生效
interactive_timeout=1800
wait_timeout=1800
#Metadata Lock最大时长(秒), 一般用于控制 alter操作的最大时长sine mysql5.6
#执行 DML操作时除了增加innodb事务锁外还增加Metadata Lock,其他alter(DDL)session将阻塞
lock_wait_timeout=3600
#内部内存临时表的最大值。
#比如大数据量的group by ,order by时可能用到临时表,
#超过了这个值将写入磁盘,系统IO压力增大
tmp_table_size=64M
max_heap_table_size=64M
[mysql]
# 设置mysql客户端默认字符集
default-character-set=utf8mb4
[client]
# 设置mysql客户端连接服务端时默认使用的端口
port=3306
default-character-set=utf8mb4
# Custom config should go here
!includedir /etc/mysql/conf.d/
创建容器
参数解释:
-v : 挂载宿主机目录和 docker容器中的目录,前面是宿主机目录,后面是容器内部目录
-d : 后台运行容器
-p 映射容器端口号和宿主机端口号
-e 环境参数,MYSQL_ROOT_PASSWORD设置root用户的密码

docker run -d --name mysql -p 3306:3306 \
 --restart always --privileged=true \
 -v /opt/mysql/conf/my.cnf:/etc/mysql/my.cnf \
 -v /opt/mysql/data:/var/lib/mysql/data \
 -v /opt/mysql/logs:/var/log/mysql \
 -e MYSQL_ROOT_PASSWORD=123456 mysql:8.0.27 \
 --character-set-server=utf8mb4 --collation-server=utf8mb4_general_ci
容器内部操作
# 进入容器内部
docker exec -it mysql /bin/bash

# 连接mysql
mysql -uroot -p

# 使用mysql库
use mysql;

# 修改密码
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '新密码';

# 刷新
flush privileges;

nacos

下载镜像
docker pull nacos/nacos-server:1.4.2
创建容器
docker run --name nacos -e MODE=standalone -p 8848:8848 -d nacos/nacos-server:1.4.2
运行初始化语句
# mysql上创建nacos_config库
https://github.com/alibaba/nacos/blob/master/distribution/conf/nacos-mysql.sql
配置nacos目录
# 后面会把初始的nacos目录拷贝出来,这步可以不做

# 创建 nacos配置存放目录
mkdir -p /opt/nacos/conf  && chown -R 200 /opt/nacos/conf

# 创建 nacos日志存放目录
mkdir -p /opt/nacos/logs  && chown -R 200 /opt/nacos/logs

# 创建 nacos数据存放目录
mkdir -p /opt/nacos/data  && chown -R 200 /opt/nacos/data
自定义nacos配置文件
vim /opt/nacos_custom.properties

server.contextPath=/nacos
server.servlet.contextPath=/nacos
server.port=8848

spring.datasource.platform=mysql

db.num=1
db.url.0=jdbc:mysql://172.168.10.168:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=nacos
db.password=nacos

nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false

management.metrics.export.elastic.enabled=false

management.metrics.export.influx.enabled=false

server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i

nacos.security.ignore.urls=/,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/login,/v1/console/health/**,/v1/cs/**,/v1/ns/**,/v1/cmdb/**,/actuator/**,/v1/console/server/**
nacos.naming.distro.taskDispatchThreadCount=1
nacos.naming.distro.taskDispatchPeriod=200
nacos.naming.distro.batchSyncKeyCount=1000
nacos.naming.distro.initDataRatio=0.9
nacos.naming.distro.syncRetryDelay=5000
nacos.naming.data.warmup=true
nacos.naming.expireInstance=true
运行容器
docker  run \
--name nacos -d \
-p 8848:8848 \
--privileged=true \
--restart=always \
-e JVM_XMS=256m \
-e JVM_XMX=256m \
-e MODE=standalone \
-e PREFER_HOST_MODE=172.168.10.168 \
-v /opt/nacos/logs:/home/nacos/logs \
-v /opt/nacos_custom.properties:/home/nacos/init.d/custom.properties \
nacos/nacos-server:1.4.2
复制容器内文件
# 把容器中的 nacos 文件复制出来
docker cp -a nacos:/home/nacos /opt/ 

# 删除 nacos 容器 
docker rm -f nacos
再次创建nacos容器
docker  run \
--name nacos -d \
-p 8848:8848 \
--privileged=true \
--restart=always \
-e JVM_XMS=256m \
-e JVM_XMX=256m \
-e MODE=standalone \
-e PREFER_HOST_MODE=172.168.10.168 \
-v /opt/nacos/conf:/home/nacos/conf \
-v /opt/nacos/logs:/home/nacos/logs \
-v /opt/nacos/data:/home/nacos/data \
-v /opt/nacos_custom.properties:/home/nacos/init.d/custom.properties \
nacos/nacos-server:1.4.2
nacos登录
http://172.168.10.168:8848/nacos
默认用户名: nacos
默认密码: nacos

seata

下载镜像
docker pull seataio/seata-server:1.4.2
配置文件 : registry.conf
vim /opt/seata/config/registry.comf

registry {  
  #注册中心配置
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"  #注册中心类型

  nacos {
    application = "seata-server"
    serverAddr = "172.168.10.168:8848"
    group = "SEATA_GROUP"
    namespace = "seata"
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
  file {
    name = "file.conf"
  }
}

config {  #配置中心
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"  #配置中心类型,初学建议使用默认配置file

  nacos {
    serverAddr = "172.168.10.168:8848"
    namespace = "seata"
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
    dataId = "seataServer.properties"
  }
  file {
    name = "file.conf"
  }
}
配置文件 : file.conf
vim /opt/seata/config/file.comf

## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  mode = "db"

  ## database store property
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"

    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.cj.jdbc.Driver"
    ## if using mysql to store the data, recommend add rewriteBatchedStatements=true in jdbc connection param
    url = "jdbc:mysql://172.168.10.168:3306/seata?rewriteBatchedStatements=true"
    user = "root"
    password = "123456"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }
}
mysql上创建seata库
-- -------------------------------- 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_gmt_modified_status` (`gmt_modified`, `status`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- 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 = utf8;

-- 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),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

# undo_log 在需要分布式事务的数据库上执行sql,seata库也执行一份
create table undo_log
(
    branch_id     bigint       not null comment 'branch transaction id',
    xid           varchar(100) 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          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',
    constraint ux_undo_log
        unique (xid, branch_id)
)
    comment 'AT transaction mode undo table' charset = utf8mb4;
seata初始化配置参数 : config.txt
vim /opt/seata/config.txt

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
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
service.vgroupMapping.my_test_tx_group=default
service.default.grouplist=172.168.10.168:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
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=false
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://172.168.10.168:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
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
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
log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
执行初始化
# nacos-config.sh 在seata配置下载中可以找到
# nacos-config.sh 放在/opt/seata/config/

Parameter Description:
-h: host, the default value is localhost.
-p: port, the default value is 8848.
-g: Configure grouping, the default value is 'SEATA_GROUP'.
-t: Tenant information, corresponding to the namespace ID field of Nacos, the default value is ''.
-u: username, nacos 1.2.0+ on permission control, the default value is ''.
-w: password, nacos 1.2.0+ on permission control, the default value is ''.

sh /opt/seata/nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t seata -u nacos -w nacos
创建容器
docker run --name seata-server \
 -p 8091:8091 \
 -e SEATA_CONFIG_NAME=file:/root/seata-config/registry \
 -v /opt/seata/config:/root/seata-config \
 seataio/seata-server:1.4.2

# 查看日志,出现下列日志,说明启动成功
docker logs -f seata-server

12:09:20.076  INFO --- [                     main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
12:09:20.346  INFO --- [                     main] i.s.core.rpc.netty.NettyServerBootstrap  : Server started, listen port: 8091
在需要的项目配置文件(application.yml)加入配置
seata:
  enabled: true
  application-id: applicationName
  tx-service-group: my_test_tx_group
  service:
    vgroup-mapping:
      my_test_tx_group: default
    grouplist:
      default: 127.0.0.1:8091
    enable-degrade: false
    disable-global-transaction: false
  config:
    type: nacos
    nacos:
      namespace: seata
      server-addr: 172.168.10.168:8848
      group: SEATA_GROUP
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: 172.168.10.168:8848
      group : SEATA_GROUP
      namespace: seata
  log:
    exception-rate: 100
测试
# 增加注解

# 事务开始
@GlobalTransactional(name = "xxxxx_undo", rollbackFor = Exception.class)
# 需要分布式事务的地方
@Transactional(rollbackFor = Exception.class)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值