15、SpringCloudAlibaba第十五章,升级篇,分布式事务解决方案Seata

编程

SpringCloud Alibaba第十四章,升级篇,分布式事务解决方案Seata

一、分布式事务概述

1、什么是分布式事务

随着互联网的快速发展,软件系统由原来的单体应用转变为分布式应用。

分布式系统会把一个应用系统拆分为可独立部署的多个服务,因此需要服务与服务之间远程协作才能完成事务操作,这种分布式系统环境下由不同的服务之间通过网络远程协作完成事务称之为分布式事务。

例如用户注册送积分事务、创建订单减库存事务,银行转账事务等都是分布式事务。

1.1、 本地事务依赖数据库本身提供的事务特性来实现 :

begin transaction;

//1.本地数据库操作:张三减少金额

//2.本地数据库操作:李四增加金额

commit transation;

1.2、 但是在分布式环境下,会变成下边这样:

begin transaction;

//1.本地数据库操作:张三减少金额

//2.远程调用:让李四增加金额

commit transation;

可以设想,当远程调用让李四增加金额成功了,由于网络问题远程调用并没有返回,此时本地事务提交失败就回滚了张三减少金额的操作,此时张三和李四的数据就不一致了。

因此在分布式架构的基础上,传统数据库事务就无法使用了,张三和李四的账户不在一个数据库中甚至不在一个应用系统里,实现转账事务需要通过远程调用,由于网络问题就会导致分布式事务问题。

2、分布式事务产生场景:

2.1、 典型的场景就是微服务架构 微服务之间通过远程调用完成事务操作。 比如:订单微服务和库存微服务,下单的同时订单微服务请求库存微服务减库存。

2.2、 单体系统访问多个数据库实例 当单体系统需要访问多个数据库(实例)时就会产生分布式事务。 比如:用户信息和订单信息分别在两个MySQL实例存储,用户管理系统删除用户信息,需要分别删除用户信息及用户的订单信息,由于数据分布在不同的数据实例,需要通过不同的数据库链接去操作数据,此时产生分布式事务。

2.3、 多服务访问同一个数据库实例 比如:订单微服务和库存微服务即使访问同一个数据库也会产生分布式事务,原因就是跨JVM进程,两个微服务持有了不同的数据库链接进行数据库操作,此时产生分布式事务。

二、Seata概述

1、介绍

Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。

2、术语

XID - Transaction ID ,一个分布式事务唯一一个ID

TC - 事务协调者

维护全局和分支事务的状态,驱动全局事务提交或回滚。

TM - 事务管理器

定义全局事务的范围:开始全局事务、提交或回滚全局事务。

RM - 资源管理器

管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚。

3、Seata处理流程

1、TM向TC申请开启一个全局事务,全局事务创建成功,并生成一个全局唯一的ID,即XID.

2、XID在微服务调用链路的上下文间传播.

3、RM向TC注册分支事务,将其纳入XID对应全局事务的管辖.

4、TM向TC发起针对XID的全局事务提交或回滚决议.

5、TC调度XID管辖的全部分支事务完成提交或回滚请求.

其他:

官网地址:http://seata.io/

下载地址:http://seata.io/zh-cn/blog/download.html

使用:@GlobalTransactional

三、Seata Server安装

1、解压seata-server-0.9.0.zip

2、进入conf目录修改file.conf文件:自定义事务组名称、事务存储模式、数据库连接信息

service模块自定义事务组名称:

vgroup_mapping.my_test_tx_group = "default"

修改为vgroup_mapping.my_test_tx_group = "seataTxGroup"

store模块修改事务存储模式:

mode = "file"

修改为mode="db"

db模块修改为你的数据库连接:

url = "jdbc:mysql://127.0.0.1:3306/seata"

user = "root"

password = "admin123"

3、根据上面的数据库连接创建对应的库和表

CREATE SCHEMA `seata` DEFAULT CHARACTER SET utf8 ;

对应表的SQL在conf目录下的db_store.sql文件里:

global_table、branch_table、lock_table三张表

4、修改conf下的registry.conf文件,将seata注册进对应的注册中心

将registry模块下的type = "file"修改为你对应的注册中心type="nacos"

同时修改对应的注册中心模块:

nacos {

serverAddr = "localhost:8848"

namespace = ""

cluster = "seataTxGroup" ##对应的seata自定义的事务组名称

}

conf模块的file就是我们修改的file.conf文件,你也可以将conf注册信息的内容修改到nacos里

测试:

1、启动nacos server,端口号为8848

2、启动seata server

看看nacos的服务列表是否有seata server的注入,对应的端口是8901

四、Seata案例

案例为:订单--库存--用户金额账户三个微服务之间的事务

1、创建订单

2、修改订单购买的商品对应的库存,

3、并在用户金额账户中扣除购买所需金额

4、最后修改订单状态

1、创建对应的微服务表

订单表:

CREATE DATABASE seata_order;

use 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;

SELECT * FROM t_order;

库存表:

CREATE DATABASE seata_storage;

use 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(`id`,`product_id`,`total`,`used`,`residue`)

VALUES("1","1","100","0","100");

SELECT * FROM t_storage;

账户表:

CREATE DATABASE seata_account;

use 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 seata_account.t_account(`id`,`user_id`,`total`,`used`,`residue`) VALUES("1","1","1000","0","1000");

SELECT * FROM t_account;

2、创建对应的回滚日志表

##订单-库存-账户3个库下都需要建各自的回滚日志表泳衣记录每个XID

##对应的SQL在seata server的conf目录下db_undo_log.sql

-- the table to store seata xid data

-- 0.7.0+ add context

-- you must to init this sql for you business databese. the seata server not need it.

-- 此脚本必须初始化在你当前的业务数据库中,用于AT 模式XID记录。与server端无关(注:业务数据库)

-- 注意此处0.3.0+ 增加唯一索引 ux_undo_log

DROP TABLE IF EXISTS `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-order-service-2003

<parent>

<artifactId>cloud_2020</artifactId>

<groupId>com.lee.springcloud</groupId>

<version>1.0-SNAPSHOT</version>

</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>seata-order-service-2003</artifactId>

POM

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<parent>

<artifactId>cloud_2020</artifactId>

<groupId>com.lee.springcloud</groupId>

<version>1.0-SNAPSHOT</version>

</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>seata-order-service-2003</artifactId>

<dependencies>

<!--nacos-->

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

</dependency>

<!--seata-->

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-seata</artifactId>

<exclusions>

<exclusion>

<artifactId>seata-all</artifactId>

<groupId>io.seata</groupId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>io.seata</groupId>

<artifactId>seata-all</artifactId>

<version>0.9.0</version>

</dependency>

<!--feign-->

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

<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.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

<version>1.1.10</version>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

</dependencies>

</project>

application.yml

server:

port: 2003

spring:

application:

name: seata-account-service

cloud:

alibaba:

seata:

tx-service-group: my_test_tx_group #和seata-server conf目录下的file.conf中的自定义事务组名称一致

nacos:

discovery:

server-addr: localhost:8848

datasource:

driver-class-name: com.mysql.jdbc.Driver

url: jdbc:mysql://localhost:3306/seata_account

username: root

password: admin123

feign:

hystrix:

enabled: false

logging:

level:

io:

seata: info

mybatis:

mapperLocations: classpath:mapper/*.xml

同时将:seata-server conf目录下的file.conf和register.conf两个文件拷贝到resource目录

实体类

@Data

@AllArgsConstructor

@NoArgsConstructor

public class Account {

private Long id;

private Long userId;

private BigDecimal total;

private BigDecimal used;

private BigDecimal residue;

}

@Data

@ToString

@AllArgsConstructor

@NoArgsConstructor

public class CommonResult<T>

{

private Integer code;

private String message;

private T data;

public CommonResult(Integer code, String message)

{

this(code,message,null);

}

}

数据层

@Mapper

public interface AccountDao {

//扣减账户余额

void decrease(@Param("userId") Long userId, @Param("money") BigDecimal money);

}

resource/mapper目录

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.lee.springcloud.dao.AccountDao">

<resultMap id="BaseResultMap" type="com.lee.springcloud.domain.Account">

<id column="id" property="id" jdbcType="BIGINT"/>

<result column="user_id" property="userId" jdbcType="BIGINT"/>

<result column="total" property="total" jdbcType="DECIMAL"/>

<result column="used" property="used" jdbcType="DECIMAL"/>

<result column="residue" property="residue" jdbcType="DECIMAL"/>

</resultMap>

<update id="decrease">

UPDATE t_account SET

residue = residue - #{money},used = used + #{money}

WHERE user_id = #{userId};

</update>

</mapper>

服务层

public interface AccountService {

//扣减账户余额

void decrease( Long userId,BigDecimal money);

}

@Slf4j

@Service

public class AccountServiceImpl implements AccountService {

@Resource

private AccountDao accountDao;

//扣减账户余额

@Override

public void decrease(Long userId, BigDecimal money) {

log.info("------->account-service中扣减账户余额开始");

//try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }

accountDao.decrease(userId,money);

log.info("------->account-service中扣减账户余额结束");

}

}

controller

@RestController

public class AccountController {

@Resource

private AccountService accountService;

//扣减账户余额

@RequestMapping("/account/decrease")

public CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money){

accountService.decrease(userId,money);

return new CommonResult<>(200,"扣减账户余额成功!");

}

}

配置层:

@Configuration

@MapperScan({"com.lee.springcloud.dao"})

public class MybatisConfig {

}

@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(mapperLocations));

sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());

return sqlSessionFactoryBean.getObject();

}

}

主启动类

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

@EnableDiscoveryClient

@EnableFeignClients

public class SeataAccountMainApp2003 {

public static void main(String[] args){

SpringApplication.run(SeataAccountMainApp2003.class, args);

}

}

4、创建对应的微服务--库存

创建库存微服务:seata-order-service-2002

<parent>

<artifactId>cloud_2020</artifactId>

<groupId>com.lee.springcloud</groupId>

<version>1.0-SNAPSHOT</version>

</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>seata-order-service-2002</artifactId>

POM

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<parent>

<artifactId>cloud_2020</artifactId>

<groupId>com.lee.springcloud</groupId>

<version>1.0-SNAPSHOT</version>

</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>seata-order-service-2002</artifactId>

<dependencies>

<!--nacos-->

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

</dependency>

<!--seata-->

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-seata</artifactId>

<exclusions>

<exclusion>

<artifactId>seata-all</artifactId>

<groupId>io.seata</groupId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>io.seata</groupId>

<artifactId>seata-all</artifactId>

<version>0.9.0</version>

</dependency>

<!--feign-->

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

<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.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

</dependencies>

</project>

application.yml

server:

port: 2002

spring:

application:

name: seata-storage-service

cloud:

alibaba:

seata:

tx-service-group: my_test_tx_group #和seata-server conf目录下的file.conf中的自定义事务组名称一致

nacos:

discovery:

server-addr: localhost:8848

datasource:

driver-class-name: com.mysql.jdbc.Driver

url: jdbc:mysql://localhost:3306/seata_storage

username: root

password: admin123

logging:

level:

io:

seata: info

mybatis:

mapperLocations: classpath:mapper/*.xml

同时将:seata-server conf目录下的file.conf和register.conf两个文件拷贝到resource目录

实体类

@Data

@AllArgsConstructor

@NoArgsConstructor

public class CommonResult<T>

{

private Integer code;

private String message;

private T data;

public CommonResult(Integer code, String message)

{

this(code,message,null);

}

}

@Data

@ToString

@AllArgsConstructor

@NoArgsConstructor

public class Storage {

private Long id;

// 产品id

private Long productId;

//总库存

private Integer total;

//已用库存

private Integer used;

//剩余库存

private Integer residue;

}

数据层:

@Mapper

public interface StorageDao {

//扣减库存信息

void decrease(@Param("productId") Long productId, @Param("count") Integer count);

}

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.lee.springcloud.dao.StorageDao">

<resultMap id="BaseResultMap" type="com.lee.springcloud.domain.Storage">

<id column="id" property="id" jdbcType="BIGINT"/>

<result column="product_id" property="productId" jdbcType="BIGINT"/>

<result column="total" property="total" jdbcType="INTEGER"/>

<result column="used" property="used" jdbcType="INTEGER"/>

<result column="residue" property="residue" jdbcType="INTEGER"/>

</resultMap>

<update id="decrease">

UPDATE

t_storage

SET

used = used + #{count},residue = residue - #{count}

WHERE

product_id = #{productId}

</update>

</mapper>

服务层

public interface StorageService {

// 扣减库存

void decrease(Long productId, Integer count);

}

@Slf4j

@Service

public class StorageServiceImpl implements StorageService {

@Resource

private StorageDao storageDao;

// 扣减库存

@Override

public void decrease(Long productId, Integer count) {

log.info("------->storage-service中扣减库存开始");

storageDao.decrease(productId,count);

log.info("------->storage-service中扣减库存结束");

}

}

controller

@RestController

public class StorageController {

@Autowired

private StorageService storageService;

//扣减库存

@RequestMapping("/storage/decrease")

public CommonResult decrease(Long productId, Integer count) {

storageService.decrease(productId, count);

return new CommonResult(200,"扣减库存成功!");

}

}

config

@Configuration

@MapperScan({"com.lee.springcloud.dao"})

public class MybatisConfig {

}

@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(mapperLocations));

sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());

return sqlSessionFactoryBean.getObject();

}

}

主启动类:

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

@EnableDiscoveryClient

@EnableFeignClients

public class SeataStorageServiceApplication2002

{

public static void main(String[] args)

{

SpringApplication.run(SeataStorageServiceApplication2002.class, args);

}

}

5、创建对应的微服务--订单

创建对应的订单微服务:seata-order-service-2001

<parent>

<artifactId>cloud_2020</artifactId>

<groupId>com.lee.springcloud</groupId>

<version>1.0-SNAPSHOT</version>

</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>seata-order-service-2001</artifactId>

POM

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<parent>

<artifactId>cloud_2020</artifactId>

<groupId>com.lee.springcloud</groupId>

<version>1.0-SNAPSHOT</version>

</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>seata-order-service-2001</artifactId>

<dependencies>

<!--nacos-->

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>

</dependency>

<!--seata-->

<dependency>

<groupId>com.alibaba.cloud</groupId>

<artifactId>spring-cloud-starter-alibaba-seata</artifactId>

<exclusions>

<exclusion>

<artifactId>seata-all</artifactId>

<groupId>io.seata</groupId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>io.seata</groupId>

<artifactId>seata-all</artifactId>

<version>0.9.0</version>

</dependency>

<!--feign-->

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

<!--web-actuator-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

<!--mysql-druid-->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

</dependency>

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

</dependencies>

</project>

application.yml

server:

port: 2001

spring:

application:

name: seata-order-service

cloud:

alibaba:

seata:

tx-service-group: my_test_tx_group #自定义事务组名称需要与seata-server中的对应

nacos:

discovery:

server-addr: localhost:8848

datasource:

driver-class-name: com.mysql.jdbc.Driver

url: jdbc:mysql://localhost:3306/seata_order

username: root

password: admin123

feign:

hystrix:

enabled: false

logging:

level:

io:

seata: info

mybatis:

mapperLocations: classpath:mapper/*.xml

同时将:seata-server conf目录下的file.conf和register.conf两个文件拷贝到resource目录

实体类

@Data

@AllArgsConstructor

@NoArgsConstructor

public class CommonResult<T>

{

private Integer code;

private String message;

private T data;

public CommonResult(Integer code, String message)

{

this(code,message,null);

}

}

@Data

@ToString

@AllArgsConstructor

@NoArgsConstructor

public class Order{

private Long id;

private Long userId;

private Long productId;

private Integer count;

private BigDecimal money;

private Integer status; //订单状态:0:创建中;1:已完结

}

数据层

@Mapper

public interface OrderDao{

//新建订单

void create(Order order);

//修改订单状态,从零改为1

void update(@Param("userId") Long userId, @Param("status") Integer status);

}

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.lee.springcloud.dao.OrderDao">

<resultMap id="BaseResultMap" type="com.lee.springcloud.domain.Order">

<id column="id" property="id" jdbcType="BIGINT"/>

<result column="user_id" property="userId" jdbcType="BIGINT"/>

<result column="product_id" property="productId" jdbcType="BIGINT"/>

<result column="count" property="count" jdbcType="INTEGER"/>

<result column="money" property="money" jdbcType="DECIMAL"/>

<result column="status" property="status" jdbcType="INTEGER"/>

</resultMap>

<insert id="create">

insert into t_order (id,user_id,product_id,count,money,status)

values (null,#{userId},#{productId},#{count},#{money},0);

</insert>

<update id="update">

update t_order set status = 1

where user_id=#{userId} and status = #{status};

</update>

</mapper>

服务层

public interface OrderService {

void create(Order order);

}

@Service

@Slf4j

public class OrderServiceImpl implements OrderService {

@Resource

private OrderDao orderDao;

@Resource

private StorageService storageService;

@Resource

private AccountService accountService;

/**

* 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态

*/

@Override

//@GlobalTransactional(name = "test-create-order",rollbackFor = Exception.class)

public void create(Order order){

log.info("----->开始新建订单");

//新建订单

orderDao.create(order);

//扣减库存

log.info("----->订单微服务开始调用库存,做扣减Count");

storageService.decrease(order.getProductId(),order.getCount());

log.info("----->订单微服务开始调用库存,做扣减end");

//扣减账户

log.info("----->订单微服务开始调用账户,做扣减Money");

accountService.decrease(order.getUserId(),order.getMoney());

log.info("----->订单微服务开始调用账户,做扣减end");

//修改订单状态,从零到1代表已经完成

log.info("----->修改订单状态开始");

orderDao.update(order.getUserId(),0);

log.info("----->修改订单状态结束");

log.info("----->下订单结束了");

}

}

feign

@FeignClient(value = "seata-storage-service")

public interface StorageService{

@PostMapping(value = "/storage/decrease")

CommonResult decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count);

}

@FeignClient(value = "seata-account-service")

public interface AccountService{

@PostMapping(value = "/account/decrease")

CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);

}

controller

@RestController

public class OrderController{

@Resource

private OrderService orderService;

@GetMapping("/order/create")

public CommonResult create(Order order)

{

orderService.create(order);

return new CommonResult(200,"订单创建成功");

}

}

配置类

@Configuration

@MapperScan({"com.lee.springcloud.dao"})

public class MybatisConfig {

}

@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(mapperLocations));

sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());

return sqlSessionFactoryBean.getObject();

}

}

主启动类

@EnableDiscoveryClient

@EnableFeignClients

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动创建的配置

public class SeataOrderMainApp2001{

public static void main(String[] args)

{

SpringApplication.run(SeataOrderMainApp2001.class, args);

}

}

6、测试

1、启动nacos-server、seata-server、seata-order-service-200120022003

2、此时order微服务没有开启全局事务

//@GlobalTransactional(name = "test-create-order",rollbackFor = Exception.class)

account微服务扣款接口的延迟也没有开启

//try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }

一切正常

浏览器调用:http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100

结果:

{"code":200,"message":"订单创建成功","data":null}

数据库对应的表都做了相应的更改

3、现在我们将account微服务扣款接口延迟,因为openFeign的默认调用时长为1s,如果超过1s则调用失败

将try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }注释打开

浏览器访问:http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100

报错:java.net.SocketTimeoutException: Read timed out

数据库对应的表:

订单表数据新增了,但status为0创建中

库存表数据被修改了used10 residue90

账户表没动

4、现在我们再将全局事务打开

@GlobalTransactional(name = "test-create-order",rollbackFor = Exception.class)

浏览器访问:http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100

报错:java.net.SocketTimeoutException: Read timed out

数据库对应的表:

没有改变

以上是 15、SpringCloudAlibaba第十五章,升级篇,分布式事务解决方案Seata 的全部内容, 来源链接: utcz.com/z/516303.html

回到顶部