其他网址
Seata实现Sprincloud(Eureka+Feign)事务 - LifeOfCoding - 博客园
使用Seata彻底解决Spring Cloud中的分布式事务问题!
官方demo
总网址:https://github.com/seata/seata-samples
本文对应网址:https://github.com/seata/seata-samples/tree/master/springcloud-eureka-feign-mybatis-seata
seata+mybatis-plus
用法
SpringBoot+Dubbo+MybatisPlus整合seata分布式事务
mp增强组件失效原因分析
http://seata.io/zh-cn/blog/seata-mybatisplus-analysis.html
解决seata代理数据源后mybatisplus的增强组件全部失效的bug_FUNKYE的博客-CSDN博客_seata代理数据源
综述
本文测试Seata AT模式。
业务场景:创建订单时,order微服务先预生成订单(订单状态为创建中),再调用storage的feign来减库存,再调用account的feign来减账户余额,最后将订单状态改为已完成。
所用技术栈:spring-cloud-alibaba-seata:2.1.0.RELEASE、seata-all:1.4.0、springboot:2.3.7.RELEASE、springcloud:Hoxton.SR9、mysql、mybatis-plus、eureka、gateway。
所用插件:lombok
配置方式:
seata-server:file.conf、registry.conf
微服务:file.conf、registry.conf已知问题:所有的feign都被seata代理,必须加@GlobalTransactional。否则报错:“xid must not be blank”
本文源码:https://gitee.com/shapeless/demo_SpringCloud/tree/seata-at-1
seata-server安装/配置
下载seata服务
配置
本处使用mysql、eureka,未使用配置中心。
修改的文件:seata-server-1.4.0\seata\conf\ file.cof、registry.conf
file.conf //配置事务的存储方式。改动点已经加粗。
## transaction log store, only used in seata-server
store {
## store mode: file、db、redis
# mode = "file"
mode = "db" #将事务信息存到数据库中。配置为"db"时,只有“db”节点下的配置有效,不用管“file”## 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/seata"
## user = "mysql"
## password = "mysql"
driverClassName = "com.mysql.cj.jdbc.Driver" #使用mysql8.x驱动
url: "jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8" #指定服务器地址及数据库等
user = "xxx"
password = "xxx"
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 {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
#type = "file"
type = "eureka"
loadBalance = "RandomLoadBalance"
loadBalanceVirtualNodes = 10nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = ""
cluster = "default"
username = ""
password = ""
}
eureka {
# serviceUrl = "http://localhost:8761/eureka"
serviceUrl = "http://localhost:7001/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 = "file"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"
}
}
建库建表
创建数据库
创建名为demo的数据库。
seata服务事务表
这几张表用于seata-server存储事务。在上边file.conf指定的数据库里创建如下表:
//有人说这些语句在seata-server-xxx/conf/db_store.sql里。但我没找到,可能新的seata-server已经没有了。
-- -------------------------------- 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 `t_order` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `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 '金额', `create_time` datetime(0) NULL DEFAULT NULL, `update_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; ALTER TABLE `t_order` ADD COLUMN `status` int(1) DEFAULT NULL COMMENT '订单状态:0:创建中;1:已完结' AFTER `money` ;
踩坑:其他教程表名是"order",我用mybatis-plus时,会报错。因为,它插入数据时语句是:INSERT INTO order ...,表名没有用``包裹,而order是mysql关键字,所以报错。
CREATE TABLE `t_account` ( `id` bigint(11) NOT NULL AUTO_INCREMENT 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 '剩余可用额度', `create_time` datetime(0) NULL DEFAULT NULL, `update_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; # INSERT INTO `seat-account`.`account` (`id`, `user_id`, `total`, `used`, `residue`) VALUES ('1', '1', '1000', '0', '100'); INSERT INTO `demo`.`t_account` (`id`, `user_id`, `total`, `used`, `residue`) VALUES ('1', '1', '1000', '0', '1000');
CREATE TABLE `t_storage` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `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 '剩余库存', `create_time` datetime(0) NULL DEFAULT NULL, `update_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0), PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; # INSERT INTO `seat-storage`.`storage` (`id`, `product_id`, `total`, `used`, `residue`) VALUES ('1', '1', '100', '0', '100'); INSERT INTO `demo`.`t_storage` (`id`, `product_id`, `total`, `used`, `residue`) VALUES ('1', '1', '100', '0', '100');
业务事务表
每个被调用的服务以及服务的调用方都需要用到 "undo_log"表用于事务的回滚。
其他人都是把各个业务微服务单独用数据库,每个数据库下边都创建undo_log。但本处,我把各个业务微服务共用一个数据库,每一个业务微服务都创建一个undo_log。
CREATE TABLE `t_undo_log_order` ( `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;
CREATE TABLE `t_undo_log_storage` ( `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;
CREATE TABLE `t_undo_log_account` ( `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;
业务微服务配置Seata
共用配置
1.启动类的配置
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
seata 需要使用代理的 DataSource, 因此不使用 DataSourceAutoConfiguration
2.配置Seata事务组
application.yml
spring: cloud: alibaba: seata: tx-service-group: my_tx_group
此项对应业务微服务file.conf的service节点的vgroupMapping.xxx = "default" 的xxx位置。对于本处来说,其必须配置为:vgroupMapping.my_tx_group= "default"
3.配置使用Seata对数据源进行代理
package com.example.base.config; import com.alibaba.druid.pool.DruidDataSource; import io.seata.rm.datasource.DataSourceProxy; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; @Slf4j @Configuration public class DataSourceProxyConfig { private DataSourceProxy dataSourceProxy; @Bean(name = "druidDataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource() { DruidDataSource druidDataSource = new DruidDataSource(); log.info("获取dataSource"); return druidDataSource; } @Primary @Bean("dataSource") public DataSourceProxy dataSource(@Qualifier(value = "druidDataSource") DataSource druidDataSource) { log.info("提供dataSource(代理过)"); dataSourceProxy = new DataSourceProxy(druidDataSource); return dataSourceProxy; } // 下边这些不能放开 // @Value("spring.application.name") // private String applicationName; // @Bean // public GlobalTransactionScanner globalTransactionScanner() { // log.info("配置seata"); // return new GlobalTransactionScanner(applicationName, "my_tx_group"); // } }
各自配置
需要配置file.conf和registry.conf。注意:这两个配置文件跟seata-server的配置不同。
order
file.conf配置如下:(重点已经加粗)
transport {
# tcp udt unix-domain-socket
type = "TCP"
#NIO NATIVE
server = "NIO"
#enable heartbeat
heartbeat = true
# the client batch send request enable
enableClientBatchSendRequest = true
#thread factory for netty
threadFactory {
bossThreadPrefix = "NettyBoss"
workerThreadPrefix = "NettyServerNIOWorker"
serverExecutorThread-prefix = "NettyServerBizHandler"
shareBossWorker = false
clientSelectorThreadPrefix = "NettyClientSelector"
clientSelectorThreadSize = 1
clientWorkerThreadPrefix = "NettyClientWorkerThread"
# netty boss thread size,will not be used for UDT
bossThreadSize = 1
#auto default pin or 8
workerThreadSize = "default"
}
shutdown {
# when destroy server, wait seconds
wait = 3
}
serialization = "seata"
compressor = "none"
}
service {
#transaction service group mapping# 微服务的application.yml的spring.cloud.alibaba.seata.tx-service-group也要设置为“my_tx_group”
vgroupMapping.my_tx_group = "default"
#only support when registry.type=file, please don't set multiple addresses
default.grouplist = "127.0.0.1:8091"
#degrade, current not support
enableDegrade = false
#disable seata
disableGlobalTransaction = false
}client {
rm {
asyncCommitBufferLimit = 10000
lock {
retryInterval = 10
retryTimes = 30
retryPolicyBranchRollbackOnConflict = true
}
reportRetryCount = 5
tableMetaCheckEnable = false
reportSuccessEnable = false
}
tm {
commitRetryCount = 5
rollbackRetryCount = 5
}
undo {
dataValidation = true
logSerialization = "jackson"# 这个表对应于上边“二、建库建表”=> “业务事务表 ”的表名
logTable = "t_undo_log_order"
}
log {
exceptionRate = 100
}
}
registry.conf 配置如下:(重点已经加粗)
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "eureka"nacos {
serverAddr = "localhost"
namespace = ""
cluster = "default"
}
eureka {
serviceUrl = "http://localhost:7001/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"
session.timeout = 6000
connect.timeout = 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、springCloudConfig
type = "file"nacos {
serverAddr = "localhost"
namespace = ""
group = "SEATA_GROUP"
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
app.id = "seata-server"
apollo.meta = "http://192.168.1.204:8801"
namespace = "application"
}
zk {
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
storage
file.conf
transport { # tcp udt unix-domain-socket type = "TCP" #NIO NATIVE server = "NIO" #enable heartbeat heartbeat = true # the client batch send request enable enableClientBatchSendRequest = true #thread factory for netty threadFactory { bossThreadPrefix = "NettyBoss" workerThreadPrefix = "NettyServerNIOWorker" serverExecutorThread-prefix = "NettyServerBizHandler" shareBossWorker = false clientSelectorThreadPrefix = "NettyClientSelector" clientSelectorThreadSize = 1 clientWorkerThreadPrefix = "NettyClientWorkerThread" # netty boss thread size,will not be used for UDT bossThreadSize = 1 #auto default pin or 8 workerThreadSize = "default" } shutdown { # when destroy server, wait seconds wait = 3 } serialization = "seata" compressor = "none" } service { #transaction service group mapping vgroupMapping.my_tx_group = "default" #only support when registry.type=file, please don't set multiple addresses default.grouplist = "127.0.0.1:8091" #degrade, current not support enableDegrade = false #disable seata disableGlobalTransaction = false } client { rm { asyncCommitBufferLimit = 10000 lock { retryInterval = 10 retryTimes = 30 retryPolicyBranchRollbackOnConflict = true } reportRetryCount = 5 tableMetaCheckEnable = false reportSuccessEnable = false } tm { commitRetryCount = 5 rollbackRetryCount = 5 } undo { dataValidation = true logSerialization = "jackson" logTable = "t_undo_log_storage" } log { exceptionRate = 100 } }
registry.conf
registry { # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa type = "eureka" nacos { serverAddr = "localhost" namespace = "" cluster = "default" } eureka { serviceUrl = "http://localhost:7001/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" session.timeout = 6000 connect.timeout = 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、springCloudConfig type = "file" nacos { serverAddr = "localhost" namespace = "" group = "SEATA_GROUP" } consul { serverAddr = "127.0.0.1:8500" } apollo { app.id = "seata-server" apollo.meta = "http://192.168.1.204:8801" namespace = "application" } zk { serverAddr = "127.0.0.1:2181" session.timeout = 6000 connect.timeout = 2000 username = "" password = "" } etcd3 { serverAddr = "http://localhost:2379" } file { name = "file.conf" } }
account
file.conf
transport { # tcp udt unix-domain-socket type = "TCP" #NIO NATIVE server = "NIO" #enable heartbeat heartbeat = true # the client batch send request enable enableClientBatchSendRequest = true #thread factory for netty threadFactory { bossThreadPrefix = "NettyBoss" workerThreadPrefix = "NettyServerNIOWorker" serverExecutorThread-prefix = "NettyServerBizHandler" shareBossWorker = false clientSelectorThreadPrefix = "NettyClientSelector" clientSelectorThreadSize = 1 clientWorkerThreadPrefix = "NettyClientWorkerThread" # netty boss thread size,will not be used for UDT bossThreadSize = 1 #auto default pin or 8 workerThreadSize = "default" } shutdown { # when destroy server, wait seconds wait = 3 } serialization = "seata" compressor = "none" } service { #transaction service group mapping vgroupMapping.my_tx_group = "default" #only support when registry.type=file, please don't set multiple addresses default.grouplist = "127.0.0.1:8091" #degrade, current not support enableDegrade = false #disable seata disableGlobalTransaction = false } client { rm { asyncCommitBufferLimit = 10000 lock { retryInterval = 10 retryTimes = 30 retryPolicyBranchRollbackOnConflict = true } reportRetryCount = 5 tableMetaCheckEnable = false reportSuccessEnable = false } tm { commitRetryCount = 5 rollbackRetryCount = 5 } undo { dataValidation = true logSerialization = "jackson" logTable = "t_undo_log_account" } log { exceptionRate = 100 } }
registry.conf
registry { # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa type = "eureka" nacos { serverAddr = "localhost" namespace = "" cluster = "default" } eureka { serviceUrl = "http://localhost:7001/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" session.timeout = 6000 connect.timeout = 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、springCloudConfig type = "file" nacos { serverAddr = "localhost" namespace = "" group = "SEATA_GROUP" } consul { serverAddr = "127.0.0.1:8500" } apollo { app.id = "seata-server" apollo.meta = "http://192.168.1.204:8801" namespace = "application" } zk { serverAddr = "127.0.0.1:2181" session.timeout = 6000 connect.timeout = 2000 username = "" password = "" } etcd3 { serverAddr = "http://localhost:2379" } file { name = "file.conf" } }
业务主要代码
order
controller
package com.example.order.controller; import com.example.order.entity.Order; import com.example.order.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/order") public class OrderController { @Autowired OrderService orderService; @PostMapping("create") public String create(Order order) { orderService.create(order); return "success"; } }
service
OrderService
package com.example.order.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.order.entity.Order; public interface OrderService extends IService<Order> { void create(Order order); }
OrderServiceImpl
package com.example.order.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.order.entity.Order; import com.example.order.mapper.OrderMapper; import com.example.order.service.OrderService; import io.seata.spring.annotation.GlobalTransactional; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.base.feign.StorageFeignClient; import com.example.base.feign.AccountFeignClient; import org.springframework.transaction.annotation.Transactional; @Slf4j @Service public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService { @Autowired StorageFeignClient storageFeignClient; @Autowired AccountFeignClient accountFeignClient; @Override // @Transactional @GlobalTransactional(name = "my_tx_group",rollbackFor = Exception.class) public void create(Order order) { log.info("--创建订单开始"); order.setStatus(0); save(order); log.info("--创建订单结束"); log.info("--扣减库存开始"); storageFeignClient.decreaseStorage(order.getProductId(), order.getCount()); log.info("--扣减库存结束"); // int i = 1/0; log.info("--扣减账户余额开始"); accountFeignClient.decreaseMoney(order.getUserId(), order.getMoney()); log.info("--扣减账户余额结束"); this.getBaseMapper().updateStatus(order.getId(), 1); // int i = 1/0; } }
mapper
package com.example.order.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.order.entity.Order; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; public interface OrderMapper extends BaseMapper<Order> { @Update("UPDATE `t_order` SET status = #{status} WHERE id = #{id}") int updateStatus(@Param("id") Long id, @Param("status") Integer status); }
entity
package com.example.order.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper = false) @TableName("t_order") public class Order{ @TableId(value = "id", type = IdType.AUTO) private Long id; // 用户id private Long userId; // 产品id private Long productId; // 数量 private Integer count; // 金额 private BigDecimal money; // 订单状态:0:创建中;1:已完结 private Integer status; @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; // 插入与更新都写此字段。若使用FieldFill.UPDATE,则只更新时写此字段。 @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; }
storage
controller
package com.example.storage.feign; import com.example.storage.service.StorageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class FeignController { @Autowired StorageService storageService; @PostMapping("/feign/storage/decreaseStorage") public void decreaseStorage(@RequestParam("productId")Long productId, @RequestParam("count")Integer count) { storageService.decreaseStorage(productId, count); } }
service
StorageService
package com.example.storage.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.storage.entity.Storage; public interface StorageService extends IService<Storage> { void decreaseStorage(Long productId, Integer count); }
StorageServiceImpl
package com.example.storage.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.storage.entity.Storage; import com.example.storage.mapper.StorageMapper; import com.example.storage.service.StorageService; import org.springframework.stereotype.Service; @Service public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage> implements StorageService { @Override public void decreaseStorage(Long productId, Integer count) { // int i = 1 / 0; this.getBaseMapper().decreaseStorage(productId, count); } }
mapper
package com.example.storage.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.storage.entity.Storage; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; @Repository public interface StorageMapper extends BaseMapper<Storage> { @Update("UPDATE `t_storage` SET used= used + #{count}, residue = residue - #{count} WHERE product_id = #{productId}") int decreaseStorage(@Param("productId")Long productId, @Param("count")Integer count); }
entity
package com.example.storage.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import lombok.EqualsAndHashCode; import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper = false) @TableName("t_storage") public class Storage{ @TableId(value = "id", type = IdType.AUTO) private Long id; // 产品id private Long productId; // 总库存 private Integer total; // 已用库存 private Integer used; // 剩余库存 private Integer residue; @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; // 插入与更新都写此字段。若使用FieldFill.UPDATE,则只更新时写此字段。 @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; }
account
controller
package com.example.account.feign; import com.example.account.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.math.BigDecimal; @RestController public class FeignController { @Autowired AccountService accountService; @PostMapping("/feign/account/decreaseMoney") public void decreaseMoney(@RequestParam("userId")Long userId, @RequestParam("money")BigDecimal money) { accountService.decreaseMoney(userId, money); } }
service
AccountService
package com.example.account.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.account.entity.Account; import org.springframework.web.bind.annotation.RequestParam; import java.math.BigDecimal; public interface AccountService extends IService<Account> { void decreaseMoney(Long userId, BigDecimal money); }
AccountServiceImpl
package com.example.account.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.account.entity.Account; import com.example.account.mapper.AccountMapper; import com.example.account.service.AccountService; import org.springframework.stereotype.Service; import java.math.BigDecimal; @Service public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService { @Override public void decreaseMoney(Long userId, BigDecimal money) { this.getBaseMapper().decreaseMoney(userId, money); } }
mapper
package com.example.account.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.account.entity.Account; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.RequestParam; import java.math.BigDecimal; @Repository public interface AccountMapper extends BaseMapper<Account> { @Update("UPDATE `t_account` SET residue = residue - #{money},used = used + #{money} where user_id = #{userId}") public int decreaseMoney(@Param("userId")Long userId, @Param("money") BigDecimal money); }
entity
package com.example.account.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper = false) @TableName("t_account") public class Account{ // id @TableId(value = "id", type = IdType.AUTO) private Long id; // 用户id private Long userId; // 总额度 private BigDecimal total; // 已用余额 private BigDecimal used; // 剩余可用额度 private BigDecimal residue; @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; // 插入与更新都写此字段。若使用FieldFill.UPDATE,则只更新时写此字段。 @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; }
业务次要代码
base
通用应用注解
package com.example.base.config; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.core.annotation.AliasFor; import java.lang.annotation.*; @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @MapperScan("com.example.**.mapper") @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients("com.example.base.feign") public @interface BaseApplication { @AliasFor(annotation = SpringBootApplication.class) String[] scanBasePackages() default "com.example.**"; @AliasFor(annotation = SpringBootApplication.class) Class<?>[] exclude() default DataSourceAutoConfiguration.class; }
mybatis-plus 自动填充插件
package com.example.base.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.LocalDateTime; @Configuration //@MapperScan("com.example.**.mapper") public class MyBatisPlusConfig { private static final Logger logger = LoggerFactory.getLogger(MyBatisPlusConfig.class); //自动填充插件 @Bean public MetaObjectHandler metaObjectHandler() { return new MybatisPlusAutoFillConfig(); } public class MybatisPlusAutoFillConfig implements MetaObjectHandler { // 新增时填充 @Override public void insertFill(MetaObject metaObject) { logger.info("插入:自动填充createTime和updateTime:"+ LocalDateTime.now()); setFieldValByName("createTime", LocalDateTime.now(), metaObject); setFieldValByName("updateTime", LocalDateTime.now(), metaObject); } // 修改时填充 @Override public void updateFill(MetaObject metaObject) { logger.info("更新:自动填充updateTime:" + LocalDateTime.now()); setFieldValByName("updateTime", LocalDateTime.now(), metaObject); } } }
feign定义
package com.example.base.feign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.math.BigDecimal; @FeignClient("account") public interface AccountFeignClient { @PostMapping("/feign/account/decreaseMoney") void decreaseMoney(@RequestParam("userId")Long userId, @RequestParam("money") BigDecimal money); }
package com.example.base.feign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient("storage") public interface StorageFeignClient { @PostMapping("/feign/storage/decreaseStorage") void decreaseStorage(@RequestParam("productId") Long productId, @RequestParam("count") Integer count); }
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <!-- <version>2.1.12.RELEASE</version>--> <version>2.3.7.RELEASE</version> </parent> <packaging>pom</packaging> <groupId>com.example</groupId> <artifactId>base</artifactId> <version>0.0.1-SNAPSHOT</version> <name>base</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!-- <version>8.0.21</version> 版本Spring-Boot-Parent中已带 --> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-seata</artifactId> <version>2.1.0.RELEASE</version> <exclusions> <exclusion> <groupId>io.seata</groupId> <artifactId>seata-all</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.seata</groupId> <artifactId>seata-all</artifactId> <version>1.4.0</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <!-- <version>Greenwich.SR3</version>--> <version>Hoxton.SR9</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>src/main/java</source> <source>../base</source> <!-- <source>../base/src/main/java</source>--> </sources> </configuration> </execution> </executions> </plugin> </plugins> <!-- <resources>--> <!-- <resource>--> <!-- <directory>src/main/resources</directory>--> <!-- <includes>--> <!-- <include>**/*</include>--> <!-- </includes>--> <!-- <filtering>false</filtering>--> <!-- </resource>--> <!-- <resource>--> <!-- <directory>../base/src/main/resources</directory>--> <!-- <includes>--> <!-- <include>**/*</include>--> <!-- </includes>--> <!-- <filtering>false</filtering>--> <!-- </resource>--> <!-- </resources>--> </build> </project>
eureka/gateway
eureka
启动类
package com.example.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
application.yml
server: port: 7001 spring: application: name: eureka-server eureka: instance: hostname: localhost1 client: register-with-eureka: false fetch-registry: false serviceUrl: defaultZone: http://localhost:7001/eureka/
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <!-- <version>2.0.6.RELEASE</version>--> <version>2.1.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>eureka-server</artifactId> <version>0.0.1-SNAPSHOT</version> <name>eureka-server</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <!-- <version>Finchley.SR2</version>--> <version>Greenwich.SR6</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>
gateway
启动类
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
application.yml
server: port: 6001 spring: application: name: gateway cloud: gateway: discovery: locator: enabled: true lower-case-service-id: true httpclient: ssl: use-insecure-trust-manager: true eureka: client: service-url: defaultZone: http://localhost:7001/eureka/ # 配置Gateway日志等级,输出转发细节信息 logging: level: org.springframework.cloud.gateway: debug
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>gateway</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.SR6</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
order/storage/account
说明:order/storage/account的次要代码都是一样的。只是改了唯一性的东西:spring.applicaion.name、端口号、pom.xml的artifactId以及name。
启动类
package com.example.order; import com.example.base.config.BaseApplication; import org.springframework.boot.SpringApplication; @BaseApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }
application.yml
server: port: 9011 spring: application: name: order datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8 username: root password: 222333 cloud: alibaba: seata: tx-service-group: my_tx_group eureka: client: service-Url: defaultZone: http://localhost:7001/eureka # defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka feign: hystrix: enabled: true mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.example</groupId> <artifactId>base</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath>../base/pom.xml</relativePath> </parent> <artifactId>order</artifactId> <version>0.0.1-SNAPSHOT</version> <name>order</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> </dependencies> </project>
测试
启动注册中心,启动seata服务(运行seata-server-1.4.0\seata\bin\seata-server.bat),启动gateway,启动各个业务微服务。
正常执行(使用分布式事务)
执行之前:
访问:http://localhost:6001/order/order/create?userId=1&productId=1&count=10&money=100
结果:(订单创建、库存扣减、余额扣减)
异常执行(使用分布式事务)
order微服务:在扣减库存成功后抛出异常。
代码
package com.example.order.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.order.entity.Order; import com.example.order.mapper.OrderMapper; import com.example.order.service.OrderService; import io.seata.spring.annotation.GlobalTransactional; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.base.feign.StorageFeignClient; import com.example.base.feign.AccountFeignClient; import org.springframework.transaction.annotation.Transactional; @Slf4j @Service public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService { @Autowired StorageFeignClient storageFeignClient; @Autowired AccountFeignClient accountFeignClient; @Override // @Transactional @GlobalTransactional(name = "my_tx_group",rollbackFor = Exception.class) public void create(Order order) { log.info("--创建订单开始"); order.setStatus(0); save(order); log.info("--创建订单结束"); log.info("--扣减库存开始"); storageFeignClient.decreaseStorage(order.getProductId(), order.getCount()); log.info("--扣减库存结束"); int i = 1/0; log.info("--扣减账户余额开始"); accountFeignClient.decreaseMoney(order.getUserId(), order.getMoney()); log.info("--扣减账户余额结束"); this.getBaseMapper().updateStatus(order.getId(), 1); // int i = 1/0; } }
测试
访问之前:
在访问之前,我们打个断点,到达断点后查看数据库的状态
访问:http://localhost:6001/order/order/create?userId=1&productId=1&count=10&money=100
结果(到达断点):
执行结束
1.所有服务的数据库都回滚(插入的则删掉,修改的则改回去))
2.插入的项虽然已经删掉,但自增id不会回滚。