1.業務需求
随着業務需求的變化,單體應用被拆分成微服務應用,原來的三個子產品被拆分成三個獨立的應用,分别使用獨立的資料源,業務操作需要調用三個服務來完成。此時每個服務内部的資料一緻性由本地事務來保證,但是全局的資料一緻性問題沒法保證。
制造一個分布式事務問題
這裡我們會建立三個服務,一個訂單服務,一個庫存服務,一個賬戶服務。當使用者下單時,會在訂單服務中建立一個訂單,然後通過遠端調用庫存服務來扣減下單商品的庫存,再通過遠端調用賬戶服務來扣減使用者賬戶裡面的餘額,最後在訂單服務中修改訂單狀态為已完成。該操作跨越三個資料庫,有兩次遠端調用,很明顯會有分布式事務問題。

2.資料庫準備
2.1.建立業務資料庫
seata_order:存儲訂單的資料庫;
seata_storage:存儲庫存的資料庫;
seata_account:存儲賬戶資訊的資料庫。
2.2.初始化業務表
order表
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 '金額',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
ALTER TABLE `seata-order`.`order` ADD COLUMN `status` int(1) DEFAULT NULL COMMENT '訂單狀态:0:建立中;1:已完結' AFTER `money` ;
storage表
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 '剩餘庫存',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `seata-storage`.`storage` (`id`, `product_id`, `total`, `used`, `residue`) VALUES ('1', '1', '100', '0', '100');
account表
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 '剩餘可用額度',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `seata-account`.`account` (`id`, `user_id`, `total`, `used`, `residue`) VALUES ('1', '1', '1000', '0', '1000');
建立日志復原表
使用Seata還需要在每個資料庫中建立日志表,建表sql在
seata-server的/conf/db_undo_log.sql
中。
完整資料庫示意圖
3.用戶端配置
對seata-order-service、seata-storage-service和seata-account-service三個seata的用戶端進行配置,它們配置大緻相同,我們下面以seata-order-service的配置為例;
修改application.yml檔案,自定義事務組的名稱;
spring:
application:
name: seata-account-service
cloud:
alibaba:
seata:
#自定義事務組名稱需要與seata-server中的對應
tx-service-group: fsp_tx_group
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/seata_account?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
添加并修改file.conf配置檔案,主要是修改自定義事務組名稱;
service {
#transaction service group mapping
#修改事務組名稱為:fsp_tx_group,和用戶端自定義的名稱對應
vgroup_mapping.fsp_tx_group = "default"
#only support when registry.type=file, please don't set multiple addresses
default.grouplist = "127.0.0.1:8091"
#disable seata
disableGlobalTransaction = false
}
## transaction log store, only used in seata-server
store {
## store mode: fileă€db
#修改此處将事務資訊存儲到資料庫中
mode = "db"
## file store property
file {
## store location dir
dir = "sessionStore"
}
## database store property
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
datasource = "dbcp"
## mysql/oracle/h2/oceanbase etc.
db-type = "mysql"
driver-class-name = "com.mysql.jdbc.Driver"
#修改資料庫連接配接位址
url = "jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&characterEncoding=utf-8"
#修改資料庫使用者名
user = "root"
#修改資料庫密碼
password = "123456"
}
}
添加并修改registry.conf配置檔案,主要是将注冊中心改為eureka;
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"
}
zk {
cluster = "default"
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
}
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 = "localhost"
namespace = ""
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
app.id = "seata-server"
apollo.meta = "http://192.168.1.204:8801"
}
zk {
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
在啟動類中取消資料源的自動建立:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableFeignClients
@EnableDiscoveryClient
@EnableEurekaClient //開啟Eureka用戶端
public class SeataAccountMainApp2003 {
public static void main(String[] args) {
SpringApplication.run(SeataAccountMainApp2003.class,args);
}
}
package com.it.config;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
public class DataSourceProxyConfig {
// @Value("${mybatis.mapperLocations}")
// private String mapperLocations;
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
@Bean
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
@Bean
public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSourceProxy);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
// sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
return sqlSessionFactoryBean.getObject();
}
}
package com.it.servcie.impl;
import com.it.mapper.OrderMapper;
import com.it.pojo.Order;
import com.it.servcie.AccountService;
import com.it.servcie.OrderService;
import com.it.servcie.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Resource
private OrderMapper orderMapper;
@Resource
private StorageService storageService;
@Resource
private AccountService accountService;
@GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
@Override
public void create(Order order) {
log.info("-------->開始建立新訂單");
orderMapper.create(order);
log.info("-------->新訂單建立完畢");
System.out.println(100/0);
log.info("--------訂單微服務開始調用庫存,做扣減");
storageService.decrease(order.getProductId(),order.getCount());
log.info("-------訂單微服務開始調用庫存,做扣減end");
log.info("-------訂單微服務開始調用賬戶,做扣減");
accountService.decrease(order.getUserId(),order.getMoney());
log.info("-------訂單微服務開始調用賬戶,做扣減end");
log.info("-------修改訂單狀态");
orderMapper.update(order.getUserId(),0);
log.info("-------修改訂單狀态結束");
log.info("--------下訂單結束了,哈哈哈哈");
}
}
4.使用到的子產品用戶端配置
├── seata-order-service -- 整合了seata的訂單服務
├── seata-storage-service -- 整合了seata的庫存服務
└── seata-account-service -- 整合了seata的賬戶服務