seata属于近几年开源的项目,在官网大多只详细介绍了分布式事务概念及其标准实现原理,对于实践的代码少之又少,由于seata的版本更新以及与spring的整合,再加上seata配置的多样性和灵活性,各大论坛配置也是五花八门,所以很难搭建成功,题主几乎已经是在各大搜索引擎遍历了seata的搭建版本,有这么写的,有那么写的,能这么配置的,还能那么配置的,还有缺少文件什么的,真心搞得心态爆炸,可seata这么好的开源项目,到公司后你不得成为首选,所以题主在心态一次又一次炸裂后,在大学毕业前准备总结了一套SpringCloud整合Nacos + Seata 的kotlin版的示例(推荐搭建使用kotlin搭建)。
独立学习是一件既快乐又痛苦的事情:痛苦 -> 痛苦 -> 痛苦 -> 痛苦 -> 快乐 -> 痛苦 -> … 痛苦 -> 快乐 - v - 。
Seata 是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务。
分布式事务顾名思义就是要在分布式系统中实现事务,它其实是由多个本地事务组合而成。
分布式事务是指事务的参与者、支持事务的服务器、资源服务器以及事务管理器分别位于不同的分布式系统的不同节点之上。
对于分布式事务而言几乎满足不了 ACID,其实对于单机事务而言大部分情况下也没有满足 ACID。
下载地址:https://github.com/seata/seata/releases
下载地址:https://github.com/seata/seata
下载地址:https://github.com/alibaba/nacos/releases
解压nacos二进制压缩包,为了将nacos的配置进行持久化,我们选择将配置中心的存储方式更改为msyql存储
在数据库新建nacos_config数据库,在conf目录下将找到nacos-mysql.sql文件并执行该sql文件。
在application.properties修改为如下配置,账号密码填自己的。
#*************** Config Module Related Configurations ***************#
### If user MySQL as datasource:
spring.datasource.platform=mysql
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://localhost:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=root
现在我们的nacos已经将配置持久到数据库了。
解压seata-develop压缩包和seata压缩包:
新建nacos_seata数据库,执行如下sql脚本:
-- -------------------------------- 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_gmt_modified_status` (`gmt_modified`, `status`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
-- 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 = utf8;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(96),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
CREATE TABLE `undo_log` (
`id` BIGINT (20) NOT NULL AUTO_INCREMENT,
`branch_id` BIGINT (20) NOT NULL,
`xid` VARCHAR (100) NOT NULL,
`context` VARCHAR (128) 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) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = INNODB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;
配置conf下file.conf文件:
## transaction log store, only used in seata-server
store {
## store mode: file、db、redis
mode = "db" #修改为数据库存储
## 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 = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/nacos_seata"
user = "lishuang"
password = "jiayou0000"
minConn = 5
maxConn = 100
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
## redis store property
redis {
host = "127.0.0.1"
port = "6379"
password = ""
database = "0"
minConn = 1
maxConn = 10
maxTotal = 100
queryLimit = 100
}
}
配置conf下registry.conf文件:
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos" #更改注册中心为nacos
loadBalance = "RandomLoadBalance"
loadBalanceVirtualNodes = 10
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = ""
cluster = "default"
username = ""
password = ""
}
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"
}
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
nacos {
serverAddr = "127.0.0.1:8848"
namespace = ""
group = "SEATA_GROUP"
username = ""
password = ""
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
appId = "seata-server"
apolloMeta = "http://192.168.1.204:8801"
namespace = "application"
apolloAccesskeySecret = ""
}
zk {
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
登录nacos:http://ip:8848/nacos/index.html ,默认账户密码都是:nacos,登录进去打开配置列表可以看到近50条配置记录,如果没有配置记录,请返回至 sh nacos-config.sh hostip 这一步!!!
在服务列表会看到名为 seata-server 已经注册到nacos。
父工程管理依赖,pom.xml如下:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.jiayougroupId>
<artifactId>nacos-seataartifactId>
<version>1.0-SNAPSHOTversion>
<modules>
<module>seata-consumermodule>
<module>seata-provider1module>
<module>seata-provider2module>
modules>
<packaging>pompackaging>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlingroupId>
<artifactId>kotlin-stdlib-jdk8artifactId>
<version>1.4.10version>
dependency>
<dependency>
<groupId>org.jetbrains.kotlingroupId>
<artifactId>kotlin-reflectartifactId>
<version>1.4.10version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-seataartifactId>
<version>2.2.1.RELEASEversion>
<exclusions>
<exclusion>
<groupId>io.seatagroupId>
<artifactId>seata-spring-boot-starterartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>io.seatagroupId>
<artifactId>seata-spring-boot-starterartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.22version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlingroupId>
<artifactId>kotlin-maven-pluginartifactId>
<version>1.4.10version>
<executions>
<execution>
<id>compileid>
<phase>compilephase>
<goals>
<goal>compilegoal>
goals>
execution>
executions>
plugin>
plugins>
build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>2.2.1.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Hoxton.SR5version>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-alibaba-dependenciesartifactId>
<version>2.2.1.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
project>
三个子项目我们会引入:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
dependencies>
@EnableFeignClients
@RestController
@EnableDiscoveryClient
@SpringBootApplication
open class SeataProvider8001Applciation {
companion object {
@JvmStatic
fun main(args: Array<String>) {
runApplication<SeataProvider8001Applciation>(*args)
}
}
@Autowired
private lateinit var jdbcTemplate: JdbcTemplate
@RequestMapping("save1")
open fun save1() {
jdbcTemplate.update("insert into user1 values(1,'lishuang',100)")
println("Provider8001 -> 保存成功")
}
}
server:
port: 8001
spring:
application:
name: seata-provider8001
cloud:
nacos:
server-addr: localhost:8848
alibaba:
seata:
tx-service-group: kotlin_group #事务组
datasource:
url: jdbc:mysql://localhost:3306/nacos_seata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
feign:
hystrix:
enabled: false
seata:
enabled: true
application-id: applicationName1
tx-service-group: kotlin_group #事务组
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
namespace:
serverAddr: 127.0.0.1:8848
group: SEATA_GROUP
username: "nacos"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace:
username: "nacos"
password: "nacos"
@RestController
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
open class SeataProvider8002Applciation {
companion object {
@JvmStatic
fun main(args: Array<String>) {
runApplication<SeataProvider8002Applciation>(*args)
}
}
@Autowired
private lateinit var jdbcTemplate: JdbcTemplate
@RequestMapping("save2")
open fun save2(@RequestParam("id") id: Int) {
if (id == 0)
1 / 0
jdbcTemplate.update("insert into user2 values(1,'lishuang',100)")
println("Provider8002 -> 保存成功")
}
}
server:
port: 8002
spring:
application:
name: seata-provider8002
cloud:
nacos:
server-addr: localhost:8848
alibaba:
seata:
tx-service-group: kotlin_group #事务组
datasource:
url: jdbc:mysql://localhost:3306/nacos_seata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
feign:
hystrix:
enabled: false
seata:
enabled: true
application-id: applicationName2
tx-service-group: kotlin_group #事务组
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
namespace:
serverAddr: 127.0.0.1:8848
group: SEATA_GROUP
username: "nacos"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace:
username: "nacos"
password: "nacos"
@FeignClient("seata-provider8001")
@Component
interface Api1 {
@RequestMapping("save1")
fun save1()
}
@FeignClient("seata-provider8002")
@Component
interface Api2 {
@RequestMapping("save2")
fun save2(@RequestParam("id") id: Int)
}
@EnableFeignClients
@RestController
@EnableDiscoveryClient
@SpringBootApplication
open class SeataConsumerApplciation {
companion object {
@JvmStatic
fun main(args: Array<String>) {
runApplication<SeataConsumerApplciation>(*args)
}
}
@Autowired
private lateinit var api1: Api1
@Autowired
private lateinit var api2: Api2
@RequestMapping("/save1") //未开启分布式事务,seata-provider1插入成功,seata-provider2插入失败
open fun save1() { //该分布式事务无人治理,所以并不会回滚
api1.save1()
api2.save2(0)
println("保存成功!")
}
@GlobalTransactional //开启分布式事务,seata-provider1插入成功,seata-provider2插入失败
@RequestMapping("/save2") //该分布式事务由seata事务管理器代理,在seata-provider2服务异常后会seata记录下失败的操作记录
open fun save2() { //在seata事务管理器和事务参与者们投票,有任何一个参与者异常都会导致整个分布式事务回滚
api1.save1()
api2.save2(0)
println("保存成功!")
}
@GlobalTransactional //开启分布式事务,seata-provider1插入成功,seata-provider2插入成功
@RequestMapping("/save3") //该分布式事务由seata事务管理器代理
open fun save3() { //在seata事务管理器和事务参与者们投票,没有异常发生,通知各个事务参与者们提交事务
api1.save1()
api2.save2(1)
println("保存成功!")
}
}
server:
port: 8088
spring:
application:
name: seata-consumer
cloud:
nacos:
server-addr: localhost:8848
alibaba:
seata:
tx-service-group: kotlin_group #事务组
feign:
hystrix:
enabled: false
seata:
enabled: true
application-id: applicationNameServer
tx-service-group: kotlin_group #事务组
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
namespace:
serverAddr: 127.0.0.1:8848
group: SEATA_GROUP
username: "nacos"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace:
username: "nacos"
password: "nacos"