为微服务创建 UNDO_LOG 表
-- 注意此处0.3.0+ 增加唯一索引 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;
导入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
查看生成包版本 seat-all-0.7.1
?
安装事务协调器
seat-server下载:Releases · seata/seata · GitHub
安装解压:seata-server-0.7.1
注册中心配置config/registry.conf:修改 registry type = "nacos"
启动seata-server
双击 /bin/seata-server.bat
启动后seata服务会被注册到nacos中心
每一个需要使用分布式事务,都要使用seata DataSourceProxy代理自己的数据源
package com.hdb.pingmoweb.order.config;
import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
@Configuration
public class MySeataConfig {
@Autowired
DataSourceProperties dataSourceProperties;
@Bean
public DataSource dataSource(DataSourceProperties dataSourceProperties){
HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
if(StringUtils.hasText(dataSourceProperties.getName())){
dataSource.setPoolName(dataSourceProperties.getName());
}
return new DataSourceProxy(dataSource);
}
}
每一个微服务,都必须导入registry.conf,file.conf?
文件在seata-server config目录下复制粘贴进去?
?
registry.conf
file.conf? ?修改 vgroup_mapping.{application.name}-fescar-service-group = "default"
修改后
vgroup_mapping.pingmoweb-order-fescar-service-group = "default"
修改测试分布式事务
1、给分布式大事务的入口标注@GlobalTransactional
2、每一个远程的小事务用@Transactional
@Autowired
private WareFeignService wareFeignService;
@GlobalTransactional
@Transactional
@RequestMapping("/submitOrder/{val}")
public R submitOrder(@PathVariable Long val){
wareFeignService.addWare(val+"",val+"",val+"");
OrderEntity order = new OrderEntity();
order.setMemberId(val);
order.setOrderSn(val+"");
order.setCouponId(val);
orderService.save(order);
int i = 10/0;
return R.ok();
}
@Autowired
private WareInfoService wareInfoService;
@Transactional
@RequestMapping("/addWare")
public R addWare(String address,String name,String areaCode){
WareInfoEntity wareInfo = new WareInfoEntity();
wareInfo.setAddress(address);
wareInfo.setName(name);
wareInfo.setAreacode(areaCode);
wareInfoService.save(wareInfo);
return R.ok();
}
测试结果,大事务通过添加@GlobalTransactional可以回滚子事务,使用线程异步编排子事务不会回滚。
|