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

本文介绍了分布式事务的背景及Seata的概述,详细讲解了Seata Server的安装过程,并通过一个具体的微服务案例——订单-库存-用户账户事务,阐述了Seata的使用方法,包括各微服务的创建与配置。
摘要由CSDN通过智能技术生成

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
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值