美文网首页
seata快速开始

seata快速开始

作者: 念䋛 | 来源:发表于2022-09-15 14:45 被阅读0次

    seata版本为1.5.2,要关注版本,因为版本之间的差距很大.
    官网地址:http://seata.io/zh-cn/
    server源码:https://github.com/seata/seata
    seata-server下载:
    百度下载
    链接:https://pan.baidu.com/s/1eilbSI0YdmupHYI7FroTsw
    提取码:biam
    github下载:
    https://github.com/seata/seata/releases
    nacos下载地址:https://github.com/alibaba/nacos/releases
    百度网盘下载地址
    链接:https://pan.baidu.com/s/1I4Z-vVrTTch6p4Z1FhIkOQ
    提取码:g7hg
    实例代码:
    https://gitee.com/zhangjijige/springcloudalibaba.git
    代码是借鉴来的,稍微改了一下
    本文使用的AT的方式实现分布式事务,也是最经常使用一种模式,至于其余的模式这里就不阐述了,配置中心使用nacos,seata-server(事务协调者)使用mysql的方式存储,性能会有写损失,但是稳定性好一些,也是比较常用的方式,什么是seata都可以取官网了解一下.
    1.创建数据库

    image.png
    sql语句在项目中
    2.创建seata-server(事务协调者)
    配置文件
    server:
      port: 7091
    
    spring:
      application:
        name: seata-server
    
    logging:
      config: classpath:logback-spring.xml
      file:
        path: ${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
    #1.5提供了可视化界面,用户名和密码
    console:
      user:
        username: seata
        password: seata
    
    seata:
      config:
        # support: nacos, consul, apollo, zk, etcd3
        type: nacos
        nacos:
          server-addr: 127.0.0.1:8848
          namespace:
          group: SEATA_GROUP
          username:
          password:
          ##if use MSE Nacos with auth, mutex with username/password attribute
          #access-key: ""
          #secret-key: ""
          data-id: seataServer.properties
      registry:
        # support: nacos, eureka, redis, zk, consul, etcd3, sofa
        type: nacos
        nacos:
          application: seata-server
          server-addr: 127.0.0.1:8848
          group: SEATA_GROUP
          namespace:
          cluster: default(这里后续提到很重要的配置)
          username:
          password:
          ##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
    

    启动seata-server
    seata-server.bat
    3.启动nacos
    注意在seata-server的配置文件中,data-id: seataServer.properties配置
    nacos的启动本文就是使用单机启动
    startup.cmd -m standalone
    nacos的命名空间就使用默认的public,在配置的namespace为空就可以了
    创建配置


    image.png

    service.vgroupMapping.default_tx_group=default这个配置很重要

    #这个很重要,要不然事务不起作用
    #default_tx_group和default,defaule是seata-server中  registry:中cluster的数值
    #default_tx_group是资源服务,就是写业务的服务的配置  tx-service-group: default_tx_group
    service.vgroupMapping.default_tx_group=default
    service.enableDegrade=false
    service.disableGlobalTransaction=false
    #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=
    #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.cj.jdbc.Driver
    store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
    store.db.user=root
    store.db.password=root
    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.queryLimit=100
    store.db.lockTable=lock_table
    store.db.maxWait=5000
    #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.xaerNotaRetryTimeout=60000
    server.session.branchAsyncQueueSize=5000
    server.session.enableBranchAsyncRemove=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
    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
    #Log rule configuration, for client and server
    log.exceptionRate=100
    #Metrics configuration, only for the server
    metrics.enabled=false
    metrics.registryType=compact
    metrics.exporterList=prometheus
    metrics.exporterPrometheusPort=9898
    #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
    

    3.资源服务(业务服务)
    这里要说明的是seata的配置了 nacos,项目本身也配置了nacos,两个配置都是需要的,
    注意seata-server的nacos的group和资源服务的group要保持一致,具体看git上的项目的配置,没有需要特殊说明的.
    4.使用
    AT模式的使用,还是比较简单的,只需要在服务调用的发起方标注
    @GlobalTransactional注解即可
    这里举例要回滚的
    seata.controller.TestController#testCommit方法被@GlobalTransactional标注
    更新stock表
    productService.reduceStock(id, totalAmount);
    新增订单
    orderService.save(orders);
    新增订单的方法写了一个 10/0的代码,报错误
    方法调用前


    image.png

    debug到orderService.save(orders);


    image.png
    此时stock表发生变化
    image.png
    由86变成84
    看一下undolog表的rollback_info字段数据,存储了原数据和修改后的数据
    {"@class":"io.seata.rm.datasource.undo.BranchUndoLog","xid":"172.17.171.135:8091:4602985123575644297","branchId":4602985123575644299,"sqlUndoLogs":["java.util.ArrayList",[{"@class":"io.seata.rm.datasource.undo.SQLUndoLog","sqlType":"UPDATE","tableName":"stock","beforeImage":{"@class":"io.seata.rm.datasource.sql.struct.TableRecords","tableName":"stock","rows":["java.util.ArrayList",[{"@class":"io.seata.rm.datasource.sql.struct.Row","fields":["java.util.ArrayList",[{"@class":"io.seata.rm.datasource.sql.struct.Field","name":"id","keyType":"PRIMARY_KEY","type":4,"value":1},{"@class":"io.seata.rm.datasource.sql.struct.Field","name":"count","keyType":"NULL","type":4,"value":86}]]}]]},"afterImage":{"@class":"io.seata.rm.datasource.sql.struct.TableRecords","tableName":"stock","rows":["java.util.ArrayList",[{"@class":"io.seata.rm.datasource.sql.struct.Row","fields":["java.util.ArrayList",[{"@class":"io.seata.rm.datasource.sql.struct.Field","name":"id","keyType":"PRIMARY_KEY","type":4,"value":1},{"@class":"io.seata.rm.datasource.sql.struct.Field","name":"count","keyType":"NULL","type":4,"value":84}]]}]]}}]]}
    

    继续调用orderService.save(orders);方法会报错误,整个事务回滚,stock表就会归滚到86
    这样分布式事务结束.
    还有很多的情况,比如人为的把stoke的数据改一下, 86 全局事务改为84,人为改为80,当事务回滚的时候,数据怎么恢复,还有全局事务没有提交的情况下,其实数据是已经发生了变化,那这个时候,另一个事务读取数据是多少后续的文章会分析.

    相关文章

      网友评论

          本文标题:seata快速开始

          本文链接:https://www.haomeiwen.com/subject/ixurortx.html