分布式事务框架seata快速入门-seata的搭建(一)
分布式事务框架seata快速入门-seata的使用(二)

本系列源码地址
Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。

1 安装

  1. 下载安装包:点击下载
  2. 上传到linux,解压,解压后目录:
    bin conf lib LICENSE logs

    bin: 存放启动脚本
    conf: 存放配置文件
    logs: 存放日志

2 修改配置文件

  1. 修改file.conf

    这里设置seata存储模式为db,即数据库,同时修改数据库配置,将数据库地址、用户名、密码设置为自己的,同时注意设置mysql驱动名,mysql 8以上设置为:com.mysql.cj.jdbc.Driver。如果设置为file,不需要进行额外设置

    ## transaction log store, only used in seata-server
    store {
      ## store mode: file、db、redis
      ## 设置seata存储模式为数据库,然后去修改数据库配置。如果设置为file,不需要进行额外设置
      mode = "db"
      ## rsa decryption public key
      publicKey = ""
      ## file store property
      file {
        ## store location dir
        dir = "sessionStore"
        # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
        maxBranchSessionSize = 16384
        # globe session size , if exceeded throws exceptions
        maxGlobalSessionSize = 512
        # file buffer size , if exceeded allocate new buffer
        fileWriteBufferCacheSize = 16384
        # when recover batch read size
        sessionReloadReadSize = 100
        # async, sync
        flushDiskMode = async
      }
    
      ## database store property
      db {
        ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
        datasource = "hikari"
        ## 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://127.0.0.1:3306/seata?rewriteBatchedStatements=true"
        user = "root"
        password = "xxxxxxxxx"
        minConn = 5
        maxConn = 100
        globalTable = "global_table"
        branchTable = "branch_table"
        lockTable = "lock_table"
        queryLimit = 100
        maxWait = 5000
      }
      ## redis store property
      redis {
        ## redis mode: single、sentinel
        mode = "single"
        ## single mode property
        single {
          host = "127.0.0.1"
          port = "6379"
        }
        ## sentinel mode property
        sentinel {
          masterName = ""
          ## such as "10.28.235.65:26379,10.28.235.65:26380,10.28.235.65:26381"
          sentinelHosts = ""
        }
        password = ""
        database = "0"
        minConn = 1
        maxConn = 10
        maxTotal = 100
        queryLimit = 100
      }
    }
    
  2. 修改 registry.conf
    1. 这里注册中心选择nacos,即registry.type=nacos,同时修改nacos配置
    2. 配置中心选择nacos ,即config.type=nacos,同时修改nacos配置,使用了nacos作为配置中心,那么file.conf里面所有的配置只要注册中心有的都会被覆盖,后面需要修改配置只需要去配置中心修改
    registry {
      # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
      type = "nacos"
    
      nacos {
        application = "seata-server"
        serverAddr = "127.0.0.1:8848"
        group = "SEATA_GROUP"
        namespace = "public"
        cluster = "default"
        username = "nacos"
        password = "nacos"
      }
      eureka {
        serviceUrl = "http://localhost:8761/eureka"
        application = "default"
        weight = "1"
      }
      redis {
        serverAddr = "localhost:6379"
        db = 0
        password = ""
        cluster = "default"
        timeout = 0
      }
      zk {
        cluster = "default"
        serverAddr = "127.0.0.1:2181"
        sessionTimeout = 6000
        connectTimeout = 2000
        username = ""
        password = ""
      }
      consul {
        cluster = "default"
        serverAddr = "127.0.0.1:8500"
        aclToken = ""
      }
      etcd3 {
        cluster = "default"
        serverAddr = "http://localhost:2379"
      }
      sofa {
        serverAddr = "127.0.0.1:9603"
        application = "default"
        region = "DEFAULT_ZONE"
        datacenter = "DefaultDataCenter"
        cluster = "default"
        group = "SEATA_GROUP"
        addressWaitTime = "3000"
      }
      file {
        name = "file.conf"
      }
    }
    
    config {
      # file、nacos 、apollo、zk、consul、etcd3
      type = "nacos"
    
      nacos {
        serverAddr = "127.0.0.1:8848"
        namespace = "public"
        group = "SEATA_GROUP"
        username = "nacos"
        password = "nacos"
      }
      consul {
        serverAddr = "127.0.0.1:8500"
        aclToken = ""
      }
      apollo {
        appId = "seata-server"
        ## apolloConfigService will cover apolloMeta
        apolloMeta = "http://192.168.1.204:8801"
        apolloConfigService = "http://192.168.1.204:8080"
        namespace = "application"
        apolloAccesskeySecret = ""
        cluster = "seata"
      }
      zk {
        serverAddr = "127.0.0.1:2181"
        sessionTimeout = 6000
        connectTimeout = 2000
        username = ""
        password = ""
        nodePath = "/seata/seata.properties"
      }
      etcd3 {
        serverAddr = "http://localhost:2379"
      }
      file {
        name = "file.conf"
      }
    }
    

3 上传配置到nacos配置中心

  1. 去github 下载配置到本地,地址链接,需要切换到对应的版本分支
    在这里插入图片描述

    可以下载整个工程,也可以直接获取需要的文件,我们直接获取需要的文件吧

  2. 在本地磁盘新建个文件夹用来存放现在的文件

  3. 复制一份文件 seata/script/config-center/config.txt到本地

  4. 复制一份文件 seata/script/config-center/nacos/nacos-config.sh到本地
    在这里插入图片描述

  5. 将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=127.0.0.1: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=file
    store.publicKey=""
    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
    store.db.datasource=hikari
    store.db.dbType=mysql
    store.db.driverClassName=com.mysql.cj.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.queryLimit=100
    store.db.lockTable=lock_table
    store.db.maxWait=5000
    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.maxConn=10
    store.redis.minConn=1
    store.redis.maxTotal=100
    store.redis.database=0
    store.redis.password=""
    store.redis.queryLimit=100
    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
    
  6. nacos-config.sh中的$(dirname "$PWD")替换为 “.”

  7. 本地没有git的话安装一个git,在上图文件下打开git窗口,输入命令

    sh ./nacos-config.sh -h 1.116.31.139 -p 8848 -g SEATA_GROUP -u nacos -w nacos
    
    1. -h 1.116.31.139 :指定nacos服务ip,默认是localhost
    2. -p 8848 :指定nacos端口,默认8848
    3. -g SEATA_GROUP:指定seata配置的group,默认SEATA_GROUP
    4. -u -w :指定nacos服务的用户名密码,默认都是nacos
      以上如果都是默认值,都可以省略
    ...
    Set log.exceptionRate=100 successfully
    Set transport.serialization=seata successfully
    Set transport.compressor=none successfully
    Set metrics.enabled=false successfully
    Set metrics.registryType=compact successfully
    Set metrics.exporterList=prometheus successfully
    Set metrics.exporterPrometheusPort=9898 successfully
    =========================================================================
     Complete initialization parameters,  total-count:89 ,  failure-count:0
    =========================================================================
     Init nacos config finished, please start seata-server.
    
    

    在这里插入图片描述

    至此,所有的file.conf配置全部都可以到nacos进行配置

4. 在nacos配置中心修改配置

  1. 编辑store.modedb,发布
  2. 修改store.db.driverClassNamecom.mysql.cj.jdbc.Driver,发布,我的mysql版本为8.0.17,8版本以下不需要修改
  3. 修改store.db.url为自己的,发布
  4. 修改store.db.user为自己的,发布
  5. 修改store.db.password为自己的,发布

5. 创建数据库和脚本

创建store.db.url中指定的数据库(默认为seata),并导入以下脚本。


SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for branch_table
-- ----------------------------
DROP TABLE IF EXISTS `branch_table`;
CREATE TABLE `branch_table` (
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(128) NOT NULL,
  `transaction_id` bigint(20) DEFAULT NULL,
  `resource_group_id` varchar(32) DEFAULT NULL,
  `resource_id` varchar(256) DEFAULT NULL,
  `branch_type` varchar(8) DEFAULT NULL,
  `status` tinyint(4) DEFAULT NULL,
  `client_id` varchar(64) DEFAULT NULL,
  `application_data` varchar(2000) DEFAULT NULL,
  `gmt_create` datetime(6) DEFAULT NULL,
  `gmt_modified` datetime(6) DEFAULT NULL,
  PRIMARY KEY (`branch_id`),
  KEY `idx_xid` (`xid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for global_table
-- ----------------------------
DROP TABLE IF EXISTS `global_table`;
CREATE TABLE `global_table` (
  `xid` varchar(128) NOT NULL,
  `transaction_id` bigint(20) DEFAULT NULL,
  `status` tinyint(4) NOT NULL,
  `application_id` varchar(32) DEFAULT NULL,
  `transaction_service_group` varchar(32) DEFAULT NULL,
  `transaction_name` varchar(128) DEFAULT NULL,
  `timeout` int(11) DEFAULT NULL,
  `begin_time` bigint(20) DEFAULT NULL,
  `application_data` varchar(2000) DEFAULT NULL,
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`xid`),
  KEY `idx_gmt_modified_status` (`gmt_modified`,`status`),
  KEY `idx_transaction_id` (`transaction_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for lock_table
-- ----------------------------
DROP TABLE IF EXISTS `lock_table`;
CREATE TABLE `lock_table` (
  `row_key` varchar(128) NOT NULL,
  `xid` varchar(128) DEFAULT NULL,
  `transaction_id` bigint(20) DEFAULT NULL,
  `branch_id` bigint(20) NOT NULL,
  `resource_id` varchar(256) DEFAULT NULL,
  `table_name` varchar(32) DEFAULT NULL,
  `pk` varchar(36) DEFAULT NULL,
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`row_key`),
  KEY `idx_branch_id` (`branch_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

6. 启动seata

进入seata安装 bin目录: nohup ./seata-server.sh >../logs/log.out 2>1 &,进入log.out 查看日志:

17:53:28.633  INFO --- [                     main] io.seata.config.FileConfiguration        : The file name of the operation is registry
17:53:28.637  INFO --- [                     main] io.seata.config.FileConfiguration        : The configuration file used is /usr/local/seata/seata-server-1.4.2/conf/registry.conf
17:53:29.699 ERROR --- [                     main] i.s.c.s.db.AbstractDataSourceProvider    : decryption failed,please confirm whether the ciphertext and secret key are correct! error msg: Illegal base64 character 22
17:53:30.841  INFO --- [                     main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
17:53:31.188  INFO --- [                     main] i.s.core.rpc.netty.NettyServerBootstrap  : Server started, listen port: 8091

至此,seata搭建成功了,可以在分布式项目中引入了

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐