目录
前提:请自行导入springcloud alibaba 2021.0.4.0的依赖,对应seata的1.5.2版本,提前部署好nacos
1、创建四个表(seata服务端需要连接的数据库里创建,建议单独为seata创建一个数据库,再导入这些表)
2、创建undo_log表(需要用到分布式事务的数据库都要创建这个表)
3、在nacos上创建seata命名空间(命名空间id也设置为seata),并添加两项配置
2、service.vgroupMapping.default_tx_group
2、修改/data/seata/resources/application.yml
4、上面是docker方式启动seata服务端,windows或linux启动如下
前提:请自行导入springcloud alibaba 2021.0.4.0的依赖,对应seata的1.5.2版本(版本对照可以看这里),提前部署好nacos
1、创建四个表(seata服务端需要连接的数据库里创建,建议单独为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_status_gmt_modified` (`status` , `gmt_modified`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;
-- 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 = utf8mb4;
-- 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),
`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 = InnoDB
DEFAULT 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 = InnoDB
DEFAULT 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);
2、创建undo_log表(需要用到分布式事务的数据库都要创建这个表)
-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime NOT NULL,
`log_modified` datetime NOT NULL,
`ext` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
3、在nacos上创建seata命名空间(命名空间id也设置为seata),并添加两项配置
1、seataServer.yml
service:
vgroupMapping:
default_tx_group: default
store:
db:
datasource: druid
dbType: mysql
driverClassName: com.mysql.jdbc.Driver #此处请注意 5.x版本请使用com.mysql.jdbc.Driver 8以上版本请使用 com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/seata?useUnicode=true #前面创建了四个表的数据库
user: root #数据库账号(自行修改)
password: root #数据库密码(自行修改)
globalTable: global_table
lockTable: lock_table
branchTable: branch_table
maxConn: 30
maxWait: 5000
minConn: 5
queryLimit: 100
mode: db
2、service.vgroupMapping.default_tx_group
default
4、启动seata服务端
1、把seata的配置从docker复制出来
docker run -d -p 8091:8091 -p 7091:7091 --name seata-serve seataio/seata-server:1.5.2
docker cp seata-serve:/seata-server/resources /data/seata
2、修改/data/seata/resources/application.yml
server:
port: 7091 #可视化界面端口
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${user.home}/logs/seata
extend:
logstash-appender:
destination: localhost:4560
kafka-appender:
bootstrap-servers: localhost:9092
topic: logback_to_logstash
console:
user:
username: seata
password: qcfitseata
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
server-addr: localhost:8848 #请把localhost改为宿主机的ip
namespace: seata #此处不填写,将会默认使用DEFAULT_GROUP
group: SEATA_GROUP
username: nacos #nacos的账户(请自行修改,如果没设置账号密码可以删掉这项配置)
password: nacos #nacos的密码(请自行修改,如果没设置账号密码可以删掉这项配置)
data-id: seataServer.yml #对应文章上面在nacos中添加的配置
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: seata-server
server-addr: localhost:8848 #请把localhost改为宿主机的ip
group: SEATA_GROUP
namespace: seata #此处不填写,将会默认使用DEFAULT_GROUP
cluster: default
username: nacos #nacos的账户(请自行修改,如果没设置账号密码可以删掉这项配置)
password: nacos #nacos的密码(请自行修改,如果没设置账号密码可以删掉这项配置)
#store:
# support: file 、 db 、 redis
# mode: file
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
3、启动seata(*.*.*.*请改为宿主机ip)
docker run --name seata-server -d \
-p 8091:8091 \
-p 7091:7091 \
-v /data/seata/resources:/seata-server/resources \
-e SEATA_IP=*.*.*.* \
--restart=always \
seataio/seata-server:1.5.2
4、上面是docker方式启动seata服务端,windows或linux启动如下
先在这里下载解压,修改conf/application.yml
server:
port: 7091 #可视化界面端口
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${user.home}/logs/seata
extend:
logstash-appender:
destination: localhost:4560
kafka-appender:
bootstrap-servers: localhost:9092
topic: logback_to_logstash
console:
user:
username: seata
password: qcfitseata
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: nacos
nacos:
server-addr: localhost:8848
namespace: seata #此处不填写,将会默认使用DEFAULT_GROUP
group: SEATA_GROUP
username: nacos #nacos的账户(请自行修改,如果没设置账号密码可以删掉这项配置)
password: nacos #nacos的密码(请自行修改,如果没设置账号密码可以删掉这项配置)
data-id: seataServer.yml #对应文章上面在nacos中添加的配置
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: nacos
nacos:
application: seata-server
server-addr: localhost:8848
group: SEATA_GROUP
namespace: seata #此处不填写,将会默认使用DEFAULT_GROUP
cluster: default
username: nacos #nacos的账户(请自行修改,如果没设置账号密码可以删掉这项配置)
password: nacos #nacos的密码(请自行修改,如果没设置账号密码可以删掉这项配置)
#store:
# support: file 、 db 、 redis
# mode: file
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login
然后再bin/seata-server.bat或bin/seata-server.sh启动seata服务端就可以了
5、需要使用分布式事务的微服务添加的依赖及配置
依赖
<!-- seata -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<!--seata starter -->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</dependency>
配置
seata:
application-id: seata-server
# 是否启用数据源bean的自动代理
enable-auto-data-source-proxy: false
tx-service-group: default_tx_group # 必须和服务器配置一样
registry:
type: nacos
nacos:
# Nacos 服务地址
server-addr: localhost:8848
group: SEATA_GROUP
namespace: seata
application: seata-server # 必须和服务器配置一样
username: nacos #nacos的账户(请自行修改,如果没设置账号密码可以删掉这项配置)
password: nacos #nacos的密码(请自行修改,如果没设置账号密码可以删掉这项配置)
cluster: default
config:
type: nacos
nacos:
server-addr: localhost:8848
group: SEATA_GROUP
username: nacos #nacos的账户(请自行修改,如果没设置账号密码可以删掉这项配置)
password: nacos #nacos的密码(请自行修改,如果没设置账号密码可以删掉这项配置)
namespace: seata
service:
vgroup-mapping:
default_tx_group: default # 必须和服务器配置一样
disable-global-transaction: false
client:
rm:
# 是否上报成功状态
report-success-enable: true
# 重试次数
report-retry-count: 5
手动装配数据源(排除springboot自动装配,加上两个配置类)
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
@Data
public class DataSourceConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driveClassName;
}
import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class DataSourceProxyConfig {
@Autowired
private DataSourceConfig dataSourceConfig;
@Bean("dataSource")
public DataSource druidDataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setJdbcUrl(dataSourceConfig.getUrl());
hikariDataSource.setUsername(dataSourceConfig.getUserName());
hikariDataSource.setPassword(dataSourceConfig.getPassword());
hikariDataSource.setDriverClassName(dataSourceConfig.getDriveClassName());
return hikariDataSource;
}
@Bean
@Primary
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
}
完成以上操作,就可以启用分布式事务了
在分布式事务入口添加@GlobalTransactional注解
在被远程调用的接口添加@Transactional注解(事务传播需设置为REQUIRES_NEW)
大功告成~