使用分布式事务seata 1.5.2

网友投稿 919 2022-10-17

使用分布式事务seata 1.5.2

使用分布式事务seata 1.5.2

目前使用的是1.5.2版本

官网-:https://github.com/seata/seata/tags 上传linux服务器 解压: tar -zxvf seata-server-1.5.2.tar.gz 进入conf修改 application.yml:   vim application.yml    注意替换自己的 nacos 地址 server: port: 7091

spring:application:name: seata-server

logging:config: classpath:logback-spring.xmlfile: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

console:user:username: seatapassword: seata

seata:config:

support: nacos, consul, apollo, zk, etcd3

type: nacos nacos: server-addr: 127.0.0.1:8848 namespace: zj-display-cloud group: default_tx_group username: nacos password: nacos

registry:

support: nacos, eureka, redis, zk, consul, etcd3, sofa

type: nacos nacos: application: seata-server server-addr: 127.0.0.1:8848 group: default_tx_group namespace: zj-display-cloud cluster: default username: nacos password: nacos

#store:

support: file 、 db 、 redis

mode: file

server:

service-port: 8091 #If not configured, the default is '${server.port} + 1000'

security:secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017tokenValidityInMilliseconds: 1800000ignore:urls: /,//*.css,/*/.js,//*.html,//*.map,/*/.svg,//*.png,/*/.ico,/console-fe/public/**,/api/v1/auth/login

![image.png](https://s2./images/20220818/1660793374496694.png?x-oss-process=image/watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=) ---- 1. 进入seata/script/config-center 修改 vim config.txt  注意:其实直接复制这个进入就可以了,修改数据库配置 ```bash #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 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 #Transaction storage configuration, only for the server. The file, DB, and redis configuration values are optional. #store.mode=file #store.lock.mode=file #store.session.mode=file #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=postgresql store.db.driverClassName=org.postgresql.Driver store.db.url=jdbc:postgresql://IP:5431/数据库名?useSSL=true&allowMultiQueries=true&stringtype=unspecified store.db.user=你的账号 store.db.password=你的密码 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 #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.maxConn=10 #store.redis.minConn=1 #store.redis.maxTotal=100 #store.redis.database=0 #store.redis.password= #store.redis.queryLimit=100 #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 server.enableParallelRequestHandle=false #Metrics configuration, only for the server metrics.enabled=false metrics.registryType=compact metrics.exporterList=prometheus metrics.exporterPrometheusPort=9898

mysql:

-- 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';

postgresql:

-- for AT mode you must to init this sql for you business database. the seata server not need it. CREATE TABLE IF NOT EXISTS public.undo_log ( id SERIAL NOT NULL, branch_id BIGINT NOT NULL, xid VARCHAR(128) NOT NULL, context VARCHAR(128) NOT NULL, rollback_info BYTEA NOT NULL, log_status INT NOT NULL, log_created TIMESTAMP(0) NOT NULL, log_modified TIMESTAMP(0) NOT NULL, CONSTRAINT pk_undo_log PRIMARY KEY (id), CONSTRAINT ux_undo_log UNIQUE (xid, branch_id) ); CREATE SEQUENCE IF NOT EXISTS undo_log_id_seq INCREMENT BY 1 MINVALUE 1 ;

oracle:

-- for AT mode you must to init this sql for you business database. the seata server not need it. CREATE TABLE undo_log ( id NUMBER(19) NOT NULL, branch_id NUMBER(19) NOT NULL, xid VARCHAR2(128) NOT NULL, context VARCHAR2(128) NOT NULL, rollback_info BLOB NOT NULL, log_status NUMBER(10) NOT NULL, log_created TIMESTAMP(0) NOT NULL, log_modified TIMESTAMP(0) NOT NULL, PRIMARY KEY (id), CONSTRAINT ux_undo_log UNIQUE (xid, branch_id) ); COMMENT ON TABLE undo_log IS 'AT transaction mode undo table'; -- Generate ID using sequence and trigger CREATE SEQUENCE UNDO_LOG_SEQ START WITH 1 INCREMENT BY 1;

进入seata/script/config-center/nacos执行 sh nocos-config.sh 注意看是否全部执行成功,必须保证全部执行成功后才能使用 -seata数据库的建表SQL(seata(mysql) -- -------------------------------- 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 dataCREATE 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 = InnoDBDEFAULT CHARSET = utf8mb4;

-- the table to store lock dataCREATE 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_and_branch_id (xid , branch_id)) ENGINE = InnoDBDEFAULT 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 = InnoDBDEFAULT 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(oracle) ```bash -- -------------------------------- The script used when storeMode is 'db' -------------------------------- -- the table to store GlobalSession data CREATE TABLE global_table ( xid VARCHAR2(128) NOT NULL, transaction_id NUMBER(19), status NUMBER(3) NOT NULL, application_id VARCHAR2(32), transaction_service_group VARCHAR2(32), transaction_name VARCHAR2(128), timeout NUMBER(10), begin_time NUMBER(19), application_data VARCHAR2(2000), gmt_create TIMESTAMP(0), gmt_modified TIMESTAMP(0), PRIMARY KEY (xid) ); CREATE INDEX idx_status_gmt_modified ON global_table (status, gmt_modified); CREATE INDEX idx_transaction_id ON global_table (transaction_id); -- the table to store BranchSession data CREATE TABLE branch_table ( branch_id NUMBER(19) NOT NULL, xid VARCHAR2(128) NOT NULL, transaction_id NUMBER(19), resource_group_id VARCHAR2(32), resource_id VARCHAR2(256), branch_type VARCHAR2(8), status NUMBER(3), client_id VARCHAR2(64), application_data VARCHAR2(2000), gmt_create TIMESTAMP(6), gmt_modified TIMESTAMP(6), PRIMARY KEY (branch_id) ); CREATE INDEX idx_xid ON branch_table (xid); -- the table to store lock data CREATE TABLE lock_table ( row_key VARCHAR2(128) NOT NULL, xid VARCHAR2(128), transaction_id NUMBER(19), branch_id NUMBER(19) NOT NULL, resource_id VARCHAR2(256), table_name VARCHAR2(32), pk VARCHAR2(36), status NUMBER(3) NOT NULL DEFAULT 0, gmt_create TIMESTAMP(0), gmt_modified TIMESTAMP(0), PRIMARY KEY (row_key) ); comment on column lock_table.status is '0:locked ,1:rollbacking'; CREATE INDEX idx_branch_id ON lock_table (branch_id); CREATE INDEX idx_xid ON lock_table (xid); CREATE INDEX idx_status ON lock_table (status); CREATE TABLE distributed_lock ( lock_key VARCHAR2(20) NOT NULL, lock_value VARCHAR2(20) NOT NULL, expire DECIMAL(18) NOT NULL, PRIMARY KEY (lock_key) ); 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(postgresql)

-- -------------------------------- The script used when storeMode is 'db' -------------------------------- -- the table to store GlobalSession data CREATE TABLE IF NOT EXISTS public.global_table ( xid VARCHAR(128) NOT NULL, transaction_id BIGINT, status SMALLINT 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 TIMESTAMP(0), gmt_modified TIMESTAMP(0), CONSTRAINT pk_global_table PRIMARY KEY (xid) ); CREATE INDEX idx_status_gmt_modified ON public.global_table (status, gmt_modified); CREATE INDEX idx_transaction_id ON public.global_table (transaction_id); -- the table to store BranchSession data CREATE TABLE IF NOT EXISTS public.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 SMALLINT, client_id VARCHAR(64), application_data VARCHAR(2000), gmt_create TIMESTAMP(6), gmt_modified TIMESTAMP(6), CONSTRAINT pk_branch_table PRIMARY KEY (branch_id) ); CREATE INDEX idx_xid ON public.branch_table (xid); -- the table to store lock data CREATE TABLE IF NOT EXISTS public.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 SMALLINT NOT NULL DEFAULT 0, gmt_create TIMESTAMP(0), gmt_modified TIMESTAMP(0), CONSTRAINT pk_lock_table PRIMARY KEY (row_key) ); comment on column public.lock_table.status is '0:locked ,1:rollbacking'; CREATE INDEX idx_branch_id ON public.lock_table (branch_id); CREATE INDEX idx_xid ON public.lock_table (xid); CREATE INDEX idx_status ON public.lock_table (status); CREATE TABLE distributed_lock ( lock_key VARCHAR(20) NOT NULL, lock_value VARCHAR(20) NOT NULL, expire BIGINT NOT NULL, CONSTRAINT pk_distributed_lock_table PRIMARY KEY (lock_key) ); 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/bin启动 seata : ./seata-server.sh查看日志是否启动成功,查看nacos中是否注册进来

客户端使用maven引入

io.seata seata-spring-boot-starter 1.5.2 com.alibaba.cloud spring-cloud-starter-alibaba-seata 2.2.6.RELEASE io.seata seata-spring-boot-starter

配置文件配置

cloud: nacos: username: nacos password: nacos discovery: # server-addr: 192.168.0.111:8849 # nacos服务名 server-addr: 192.168.201.128:8848 # 本地nacos服务名 service: ${spring.application.name} # 注册到nacos的服务名 namespace: zj-display-cloud # 服务命名空间 #seata使用开始 group: DEFAULT_GROUP config: group: default_tx_group #seata使用结束

这是第一级别

seata: service: vgroup-mapping: default_tx_group: default grouplist: #seata服务器ip default: 192.168.201.128:8091

在方法上加@GlobalTransactional(rollbackFor = Exception.class)即可

@Override @GlobalTransactional(rollbackFor = Exception.class) public void addUserInfo() { UserDemoPojo userDemoPojo = new UserDemoPojo(); userDemoPojo.setUserid(UUID.randomUUID().toString().replace("-", "")); userDemoPojo.setName("测试seata"); userDemoPojo.setPhone("手机号"); userDemoDao.insertUser(userDemoPojo); numbler.add(); }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序城市定位与选择,默认定位到当前城市,用户可以根据首字母检索或者搜索框查询城市
下一篇:spring @Conditional的使用与扩展源码分析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~