seata 整合到 springcloud alibaba + nacos
版本:
spring-cloud-alibaba-dependencies 2.2.2.RELEASE
nacos 2.0.3
seata 1.4.1
1.seata-server-1.4.1下载运行
官方文档:http://seata.io/zh-cn/docs/overview/what-is-seata.html
下载地址:https://github.com/seata/seata/releases 需要把运行程序和源码包都下载下来解压,源码包里有需要的数据库脚本和seata默认的nacos配置
创建seata数据库
create database 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_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;
脚本在源码包的路径如图:
进入解压后seata-server运行程序的文件夹conf
编辑file.conf,将mode改成db,修改数据库信息,内容如下:
## transaction log store, only used in seata-server
store {
## store mode: file、db、redis
## mode改成db ##
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"
## mode改成自己的数据库信息 ##
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "******"
password = "******"
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
}
}
编辑registry.conf,将registry.type和config.type改成nacos,修改nacos配置信息,内容如下:
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
## 改动
type = "nacos"
loadBalance = "RandomLoadBalance"
loadBalanceVirtualNodes = 10
## 改动
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = "851fb8ba-ac52-4ce3-b99a-ec8e3b97c080"
cluster = "default"
username = "nacos"
password = "nacos"
}
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 {
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = "851fb8ba-ac52-4ce3-b99a-ec8e3b97c080"
username = "nacos"
password = "nacos"
}
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"
}
}
将seata配置添加到nacos
在源码包找到nacos配置和推送脚本,路径参考如下图
配置文件config.txt推送到nacos前需要先改下里面的数据库配置,推送后再改比较麻烦:
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
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
## 定义自己的事物组名称,注意order_tx_group才是名称,如果不想自定义,也可以用默认的
service.vgroupMapping.order_tx_group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
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=false
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
## 存储模式改成db
store.mode=db
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
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
## 修改数据库信息
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true
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.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
store.redis.host=127.0.0.1
store.redis.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.database=0
store.redis.password=null
store.redis.queryLimit=100
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
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
log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
修改完config.txt后进入naocs文件夹,执行nacos-config.sh脚本:
./nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 851fb8ba-ac52-4ce3-b99a-ec8e3b97c080
## -h naocs地址 -p nacos端口 -g 对应的nacos分组 -t naocs的命名空间
推送结果如图:
nacos页面信息:
推送完成后进入seata-server运行程序的bin文件夹,双击seata-server.bat启动seata-server,出现如下信息则启动成功:
2.创建业务模块
创建业务数据库
create database seata_account -- 存储账户信息的数据库
CREATE TABLE t_account(
`id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'id',
`user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
`total` DECIMAL(10, 0) DEFAULT NULL COMMENT '总额度',
`used` DECIMAL(10, 0) DEFAULT NULL COMMENT '已用余额',
`residue` DECIMAL(10, 0) DEFAULT '0' COMMENT '剩余可用额度'
)ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO t_account VALUES(1, 1, 1000, 0, 1000);
create database seata_storage -- 存储库存的数据库
-- 库存表
CREATE TABLE t_storage(
`id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
`total` INT(11) DEFAULT NULL COMMENT '总库存',
`used` INT(11) DEFAULT NULL COMMENT '已用库存',
`residue` INT(11) DEFAULT NULL COMMENT '剩余库存'
)ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO t_storage VALUES(1, 1, 100, 0, 100);
create database seata_order -- 存储订单的数据库;
-- 订单表
CREATE TABLE t_order(
`id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
`product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
`count` INT(11) DEFAULT NULL COMMENT '数量',
`money` DECIMAL(11, 0) DEFAULT NULL COMMENT '金额',
`status` INT(1) DEFAULT NULL COMMENT '订单状态:0:创建中;1:已完成'
)ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-- 此脚本必须初始化在你当前的业务数据库中,用于AT模式XID记录。与server端无关
-- seata_account,seata_storage,seata_order都需要
-- 增加唯一索引ux_undo_log
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;
创建业务模块
主要建了3个模块
seata-account-service2003,seata-storage-service2002,seata-order-service2001
详细代码查看:cloud: cloud学习记录 (gitee.com)
这里简单贴下主要业务的代码和配置:
pom.xml添加seata依赖
<!--seata-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
</exclusion>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
下单方法
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDao orderDao;
@Autowired
private StorageService storageService;
@Autowired
private AccountService accountService;
/**
* 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
* 下订单->扣库存->减余额->改状态
*/
@Override
@GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
@Transactional
public void create(Order order) {
// 创建订单
log.info("------1创建订单 order : {}------", order);
orderDao.create(order);
log.info("------创建订单完成-------");
// 扣减库存
log.info("------2扣减库存 count = {}------", order.getCount());
storageService.decrease(order.getProductId(), order.getCount());
log.info("------扣减库存完成-------");
// 扣减账户余额
log.info("------3扣减账户余额 momey = {}------", order.getMoney());
accountService.decrease(order.getUserId(), order.getMoney());
log.info("------扣减账户余额完成-------");
// 修改订单状态
log.info("------4修改订单状态before-------");
orderDao.update(order.getUserId(), 0);
log.info("------修改订单状态end-------");
}
}
@RestController
@Slf4j
public class AccountController {
@Resource
private AccountService accountService;
/**
* 扣减用户账户余额
* @param userId 用户Id
* @param money 扣减金额
* @return CommenResult
*/
@PostMapping(value = "/account/decrease")
public CommenResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money){
log.info("扣减用户账户余额 userId={}, money={}", userId, money);
if(money.intValue() == 4){
// 模拟抛出一个异常回滚所有数据
throw new IllegalArgumentException("money 不能为4");
}
accountService.decrease(userId, money);
return new CommenResult(200, "扣减用户账户余额成功");
}
}
bootstrap.yml配置
spring:
application:
name: seata-account-service
cloud:
nacos:
config:
server-addr: localhost:8848
namespace: 851fb8ba-ac52-4ce3-b99a-ec8e3b97c080
discovery:
server-addr: localhost:8848
namespace: 851fb8ba-ac52-4ce3-b99a-ec8e3b97c080
application.yml配置
server:
port: 2003
spring:
application:
name: seata-account-service
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动包
url: jdbc:mysql://localhost:3306/seata_account?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
logging:
level:
io:
seata: info
mybatis:
mapperLocations: classpath:mapper/*.xml
## 添加seata 配置
seata:
tx-service-group: order_tx_group ## nacos配置的事物组
enabled: true
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace: 851fb8ba-ac52-4ce3-b99a-ec8e3b97c080
username: nacos
password: nacos
config:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace: 851fb8ba-ac52-4ce3-b99a-ec8e3b97c080
username: nacos
password: nacos
从1.3开始,不鼓励自己注册DataSourceProxy bean。如果使用的是seata starter,不需要关心DataSourceProxy(starter会自动处理它),只需注册并以旧的方式使用Datasource bean即可。
3.启动测试
测试前t_order表有两条数据
使用postman测试接口:
成功添加,日志和数据库都正常:
测试异常情况:
响应错误,数据回滚,日志和数据库都正确