seata搭建与配置
- seata服务端
数据库脚本
1 CREATE TABLE IF NOT EXISTS `global_table` 2 ( 3 `xid` VARCHAR(128) NOT NULL, 4 `transaction_id` BIGINT, 5 `status` TINYINT NOT NULL, 6 `application_id` VARCHAR(32), 7 `transaction_service_group` VARCHAR(32), 8 `transaction_name` VARCHAR(128), 9 `timeout` INT, 10 `begin_time` BIGINT, 11 `application_data` VARCHAR(2000), 12 `gmt_create` DATETIME, 13 `gmt_modified` DATETIME, 14 PRIMARY KEY (`xid`), 15 KEY `idx_gmt_modified_status` (`gmt_modified`, `status`), 16 KEY `idx_transaction_id` (`transaction_id`) 17 ) ENGINE = INNODB DEFAULT CHARSET = utf8; 18 19 -- the table to store BranchSession data 20 CREATE TABLE IF NOT EXISTS `branch_table` 21 ( 22 `branch_id` BIGINT NOT NULL, 23 `xid` VARCHAR(128) NOT NULL, 24 `transaction_id` BIGINT, 25 `resource_group_id` VARCHAR(32), 26 `resource_id` VARCHAR(256), 27 `branch_type` VARCHAR(8), 28 `status` TINYINT, 29 `client_id` VARCHAR(64), 30 `application_data` VARCHAR(2000), 31 `gmt_create` DATETIME(6), 32 `gmt_modified` DATETIME(6), 33 PRIMARY KEY (`branch_id`), 34 KEY `idx_xid` (`xid`) 35 ) ENGINE = INNODB DEFAULT CHARSET = utf8; 36 37 -- the table to store lock data 38 CREATE TABLE IF NOT EXISTS `lock_table` 39 ( 40 `row_key` VARCHAR(128) NOT NULL, 41 `xid` VARCHAR(96), 42 `transaction_id` BIGINT, 43 `branch_id` BIGINT NOT NULL, 44 `resource_id` VARCHAR(256), 45 `table_name` VARCHAR(32), 46 `pk` VARCHAR(36), 47 `gmt_create` DATETIME, 48 `gmt_modified` DATETIME, 49 PRIMARY KEY (`row_key`), 50 KEY `idx_branch_id` (`branch_id`) 51 ) ENGINE = INNODB DEFAULT CHARSET = utf8;
注册中心配置
1 registry { 2 # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa 3 type = "eureka" 4 nacos { 5 serverAddr = "localhost" 6 namespace = "" 7 cluster = "default" 8 } 9 eureka { 10 serviceUrl = "http://192.168.1.82:9320/eureka" 11 application = "seata-server" 12 weight = "1" 13 } 14 redis { 15 serverAddr = "localhost:6379" 16 db = "0" 17 } 18 zk { 19 cluster = "default" 20 serverAddr = "127.0.0.1:2181" 21 session.timeout = 6000 22 connect.timeout = 2000 23 } 24 consul { 25 cluster = "default" 26 serverAddr = "127.0.0.1:8500" 27 } 28 etcd3 { 29 cluster = "default" 30 serverAddr = "http://localhost:2379" 31 } 32 sofa { 33 serverAddr = "127.0.0.1:9603" 34 application = "default" 35 region = "DEFAULT_ZONE" 36 datacenter = "DefaultDataCenter" 37 cluster = "default" 38 group = "SEATA_GROUP" 39 addressWaitTime = "3000" 40 } 41 file { 42 name = "file.conf" 43 } 44 } 45 config { 46 # file、nacos 、apollo、zk、consul、etcd3,在这里使用文件存储 47 type = "file" 48 nacos { 49 serverAddr = "localhost" 50 namespace = "" 51 group = "SEATA_GROUP" 52 } 53 consul { 54 serverAddr = "127.0.0.1:8500" 55 } 56 apollo { 57 app.id = "seata-server" 58 apollo.meta = "http://192.168.1.204:8801" 59 namespace = "application" 60 } 61 zk { 62 serverAddr = "127.0.0.1:2181" 63 session.timeout = 6000 64 connect.timeout = 2000 65 } 66 etcd3 { 67 serverAddr = "http://localhost:2379" 68 } 69 file { 70 name = "file:/root/seata-config/file.conf" 71 } 72 }
文件配置
1 transport { 2 # tcp udt unix-domain-socket 3 type = "TCP" 4 #NIO NATIVE 5 server = "NIO" 6 #enable heartbeat 7 heartbeat = true 8 # the client batch send request enable 9 enableClientBatchSendRequest = false 10 #thread factory for netty 11 threadFactory { 12 bossThreadPrefix = "NettyBoss" 13 workerThreadPrefix = "NettyServerNIOWorker" 14 serverExecutorThreadPrefix = "NettyServerBizHandler" 15 shareBossWorker = false 16 clientSelectorThreadPrefix = "NettyClientSelector" 17 clientSelectorThreadSize = 1 18 clientWorkerThreadPrefix = "NettyClientWorkerThread" 19 # netty boss thread size,will not be used for UDT 20 bossThreadSize = 1 21 #auto default pin or 8 22 workerThreadSize = "default" 23 } 24 shutdown { 25 # when destroy server, wait seconds 26 wait = 3 27 } 28 serialization = "seata" 29 compressor = "none" 30 } 31 # service configuration, only used in client side 32 service { 33 #transaction service group mapping 34 vgroupMapping.platform_tx_group = "default" 35 #注册中心为file类型时有效 36 #default.grouplist = "192.168.1.146:8091" 37 #degrade, current not support 38 enableDegrade = false 39 #disable seata 40 disableGlobalTransaction = false 41 } 42 #client transaction configuration, only used in client side 43 client { 44 rm { 45 asyncCommitBufferLimit = 10000 46 lock { 47 retryInterval = 10 48 retryTimes = 30 49 retryPolicyBranchRollbackOnConflict = true 50 } 51 reportRetryCount = 5 52 tableMetaCheckEnable = false 53 reportSuccessEnable = false 54 sqlParserType = druid 55 } 56 tm { 57 commitRetryCount = 5 58 rollbackRetryCount = 5 59 } 60 undo { 61 dataValidation = true 62 logSerialization = "jackson" 63 logTable = "undo_log" 64 } 65 log { 66 exceptionRate = 100 67 } 68 } 69 ## transaction log store, only used in server side 70 store { 71 ## store mode: file、db 72 mode = "db" 73 ## file store property 74 file { 75 ## store location dir 76 dir = "sessionStore" 77 # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions 78 maxBranchSessionSize = 16384 79 # globe session size , if exceeded throws exceptions 80 maxGlobalSessionSize = 512 81 # file buffer size , if exceeded allocate new buffer 82 fileWriteBufferCacheSize = 16384 83 # when recover batch read size 84 sessionReloadReadSize = 100 85 # async, sync 86 flushDiskMode = async 87 } 88 ## database store property 89 db { 90 ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc. 91 datasource = "druid" 92 ## mysql/oracle/postgresql/h2/oceanbase etc. 93 dbType = "mysql" 94 driverClassName = "com.mysql.jdbc.Driver" 95 url = "jdbc:mysql://192.168.1.249:3306/seata" 96 user = "easted" 97 password = "snkEas4532T," 98 minConn = 5 99 maxConn = 30 100 globalTable = "global_table" 101 branchTable = "branch_table" 102 lockTable = "lock_table" 103 queryLimit = 100 104 maxWait = 5000 105 } 106 } 107 ## server configuration, only used in server side 108 server { 109 recovery { 110 #schedule committing retry period in milliseconds 111 committingRetryPeriod = 1000 112 #schedule asyn committing retry period in milliseconds 113 asynCommittingRetryPeriod = 1000 114 #schedule rollbacking retry period in milliseconds 115 rollbackingRetryPeriod = 1000 116 #schedule timeout retry period in milliseconds 117 timeoutRetryPeriod = 1000 118 } 119 undo { 120 logSaveDays = 7 121 #schedule delete expired undo_log in milliseconds 122 logDeletePeriod = 86400000 123 } 124 #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent 125 maxCommitRetryTimeout = "-1" 126 maxRollbackRetryTimeout = "-1" 127 rollbackRetryTimeoutUnlockEnable = false 128 } 129 ## metrics configuration, only used in server side 130 metrics { 131 enabled = false 132 registryType = "compact" 133 # multi exporters use comma divided 134 exporterList = "prometheus" 135 exporterPrometheusPort = 9898 136 }
docker运行脚本
1 docker run --name seata-server \ 2 -p 9091:9091 \ 3 -e SEATA_IP=192.168.1.146 \ 4 -e SEATA_PORT=9091 \ 5 -e STORE_MODE=db \ 6 -e SEATA_CONFIG_NAME=file:/root/seata-config/registry \ 7 -v /opt/seata-config:/root/seata-config \ 8 -v /opt/seata/logs:/root/logs/seata \ 9 -d seataio/seata-server:1.2.0
- springcloud集成seata客户端
application-local.yaml配置
1 eureka: 2 client: 3 service-url: 4 defaultZone: http://192.168.1.82:9320/eureka 5 register-with-eureka: false #是否注册到eureka 6 fetch-registry: false #本地缓存服务 7 registry-fetch-interval-seconds: 5 #eureka client刷新本地缓存时间,默认30 8 instance: 9 appname: base-logistics 10 prefer-ip-address: true 11 instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port} 12 #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(客户端告诉服务端自己会按照该规则),默认30 13 lease-renewal-interval-in-seconds: 5 14 #Eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则剔除(客户端告诉服务端按照此规则等待自己),默认90 15 lease-expiration-duration-in-seconds: 7 16 17 18 spring: 19 cloud: 20 # nacos: 21 # discovery: 22 # server-addr: 192.168.1.82:8848 23 alibaba: 24 seata: 25 tx-service-group: platform_tx_group #与file.conf中的vgroupMapping.platform_tx_group名称必须保持一致 26 seata: 27 tx-service-group: platform_tx_group #与file.conf中的vgroupMapping.platform_tx_group名称必须保持一致 28 service: 29 vgroup-mapping: 30 platform_tx_group: seata-server 31 registry: 32 eureka: 33 service-url: ${eureka.client.service-url.defaultZone} 34 weight: 1 35 type: eureka
feign调用方(服务消费者)传递xid
1 package com.easted.interceptor.feign; 2 3 import feign.RequestInterceptor; 4 import feign.RequestTemplate; 5 import io.seata.core.context.RootContext; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.util.StringUtils; 8 9 @Configuration 10 public class SeataXIDInterceptorConfig implements RequestInterceptor { 11 12 13 @Override 14 public void apply(RequestTemplate requestTemplate) { 15 // 解决seata的xid未传递 16 String xid = RootContext.getXID(); 17 if (StringUtils.isEmpty(xid)) { 18 requestTemplate.header(RootContext.KEY_XID, xid); 19 } 20 } 21 }
feign被调用方(服务提供方)
1 @Override 2 public void addInterceptors(InterceptorRegistry registry) { 3 registry.addInterceptor(new SeataHandlerInterceptor()); //拦截器,将xid放入RootContext中 4 super.addInterceptors(registry); 5 }
代理数据源配置:seata分布式事务需要使用代理数据源,通过在启动类上加@EnableAutoDataSourceProxy注解或提供以下代码
1 package com.easted.config; 2 3 import com.zaxxer.hikari.HikariDataSource; 4 import io.seata.rm.datasource.DataSourceProxy; 5 import lombok.Data; 6 import lombok.NoArgsConstructor; 7 import org.springframework.boot.context.properties.ConfigurationProperties; 8 import org.springframework.context.annotation.Bean; 9 import org.springframework.context.annotation.Configuration; 10 import org.springframework.context.annotation.Primary; 11 12 import javax.sql.DataSource; 13 14 @Configuration 15 @ConfigurationProperties(prefix = "spring.datasource") 16 @Data 17 @NoArgsConstructor 18 public class DataSourceConfiguration { 19 20 private String url; 21 22 private String username; 23 24 private String password; 25 26 private String driverClassName; 27 28 private int idle = 5; 29 30 private int idleTimeout = 600000; 31 32 private int maxPoolSize = 100; 33 34 private boolean autoCommit = true; 35 36 private int maxLifeTime = 1800000; 37 38 private int connectTimeOut = 30000; 39 40 private String connectTestQuery = "SELECT 1"; 41 42 43 @Bean 44 public DataSource dataSource() { 45 HikariDataSource dataSource =new HikariDataSource(); 46 dataSource.setJdbcUrl(url); 47 dataSource.setUsername(username); 48 dataSource.setPassword(password); 49 dataSource.setDriverClassName(driverClassName); 50 dataSource.setMinimumIdle(idle); 51 dataSource.setIdleTimeout(idleTimeout); 52 dataSource.setMaximumPoolSize(maxPoolSize); 53 dataSource.setAutoCommit(autoCommit); 54 dataSource.setMaxLifetime(maxLifeTime); 55 dataSource.setConnectionTimeout(connectTimeOut); 56 dataSource.setConnectionTestQuery(connectTestQuery); 57 return dataSource; 58 } 59 60 @Primary 61 @Bean("dataSourceProxy") 62 public DataSourceProxy dataSourceProxy(DataSource dataSource) { 63 return new DataSourceProxy(dataSource); 64 } 65 }
undo_log业务数据源sql脚本
1 CREATE TABLE `undo_log` ( 2 `id` BIGINT(20) NOT NULL AUTO_INCREMENT, 3 `branch_id` BIGINT(20) NOT NULL, 4 `xid` VARCHAR(100) NOT NULL, 5 `context` VARCHAR(128) NOT NULL, 6 `rollback_info` LONGBLOB NOT NULL, 7 `log_status` INT(11) NOT NULL, 8 `log_created` DATETIME NOT NULL, 9 `log_modified` DATETIME NOT NULL, 10 `ext` VARCHAR(100) DEFAULT NULL, 11 PRIMARY KEY (`id`), 12 UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`) 13 ) ENGINE=INNODB DEFAULT CHARSET=utf8;

浙公网安备 33010602011771号