主頁 > 後端開發 > Spring Cloud Alibaba 使用Seata解決分布式事務

Spring Cloud Alibaba 使用Seata解決分布式事務

2021-11-10 06:25:39 後端開發

為什么會產生分布式事務?

隨著業務的快速發展,網站系統往往由單體架構逐漸演變為分布式、微服務架構,而對于資料庫則由單機資料庫架構向分布式資料庫架構轉變,此時,我們會將一個大的應用系統拆分為多個可以獨立部署的應用服務,需要各個服務之間進行遠程協作才能完成事務操作,在微服務專案中通常一個大專案會被拆分為N個子專案,例如用戶中心服務,會員中心服務,支付中心服務等一系列微服務,在面臨各種業務需求時難免會產生用戶中心服務中需要呼叫會員中心服務,支付中心服務而產生呼叫鏈路;服務與服務之間通訊采用RPC遠程呼叫技術,但是每個服務中都有自己獨立的資料源,即自己獨立的本地事務;兩個服務相互進行通訊的時候,兩個本地事務互不影響,從而出現分布式事務產生的原因,

Seata簡介

Seata 是一款開源的分布式事務解決方案,致力于提供高性能和簡單易用的分布式事務服務,Seata 將為用戶提供了 AT、TCC、SAGA 和 XA 事務模式,為用戶打造一站式的分布式解決方案,

Seata核心術語

TC (Transaction Coordinator) - 事務協調者:維護全域和分支事務的狀態,驅動全域事務提交或回滾,

TM (Transaction Manager) - 事務管理器:定義全域事務的范圍:開始全域事務、提交或回滾全域事務,

RM (Resource Manager) - 資源管理器:管理分支事務處理的資源,與TC交談以注冊分支事務和報告分支事務的狀態,并驅動分支事務提交或回滾,

AT模式作業機制

根據官方說明當前:通過JDBC訪問支持本地 ACID 事務的關系型資料庫的Java應用程式才支持AT模式,

兩階段提交協議的演變:

  • 一階段:業務資料和回滾日志記錄在同一個本地事務中提交,釋放本地鎖和連接資源,
  • 二階段:
    • 提交異步化,非常快速地完成,
    • 回滾通過一階段的回滾日志進行反向補償,

更詳細可參考官方檔案: http://seata.io/zh-cn/docs/dev/mode/at-mode.html

Seata Server 部署

官方Seata配置中心資訊:https://github.com/seata/seata/blob/develop/script/config-center/config.txt
官方Seata Nacos配置部署腳本:https://github.com/seata/seata/blob/develop/script/config-center/config.txt
版本資訊與Seata Server下載地址可參考首頁介紹檔案:https://gitee.com/SimpleWu/spring-cloud-alibaba-example

Seata目錄結構說明:

  • bin:運行腳本
  • conf:組態檔
  • lib:依賴包

當前部署方式采用Nacos作為注冊中心與配置中心,

registry.conf

該配置位于conf目錄,按下以下注釋區域進行修改

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  # 使用nacos作為注冊中心
  type = "nacos"

  nacos {
    # 注冊到nacos應用名稱
    application = "seata-server"
    # nacos ip
    serverAddr = "127.0.0.1:8848"
    # 所在分組
    group = "EXAMPLE-GROUP"
    # 所在命名空間
    namespace = "7e3699fa-09eb-4d47-8967-60f6c98da94a"
    # 所在集群
    #cluster = "default"
    username = "nacos"
    password = "nacos"
  }
  eureka {
    serviceUrl = "http://localhost:8761/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
  # 使用nacos管理配置
  type = "nacos"

  nacos {
    # nacos ip
    serverAddr = "127.0.0.1:8848"
    # 所在命名空間
    namespace = "7e3699fa-09eb-4d47-8967-60f6c98da94a"
    # 所在分組
    group = "EXAMPLE-GROUP"
    username = "nacos"
    password = "nacos"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

以上內容主要修改了注冊中心與配置中心為Nacos并且修改了Nacos地址與登錄賬號/登錄密碼,命名空間,分組;

配置部署到Nacos

這里簡化了下Nacos官網下載的config.txt內容,從官網下載的配置文本以下內容標記需要修改的需要關注

#事務組 重點關注
service.vgroupMapping.my_test_tx_group=default
#服務段分組地址
service.default.grouplist=127.0.0.1:8091
#保持默認
service.enableDegrade=false
#保持默認
service.disableGlobalTransaction=false
#存盤方式選擇 db模式則資料庫
store.mode=db
#需修改
store.lock.mode=db
#需修改
store.session.mode=db
store.publicKey=
#需修改
store.db.datasource=druid
#需修改
store.db.dbType=mysql
#需修改
store.db.driverClassName=com.mysql.jdbc.Driver
#需修改
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
#需修改
store.db.user=root
#需修改
store.db.password=123456
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
client.undo.dataValidation=true
#需修改
#jackson改為kryo 解決資料庫Datetime型別問題
client.undo.logSerialization=kryo
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
log.exceptionRate=100
transport.serialization=seata
transport.compressor=none

其中該配置需要重點關注service.vgroupMapping.my_test_tx_group=default這里的配置與微服務應用中的配置必須要一致后面會描述到,

由于有時間型別是Seata回滾反序列化Date型別無法成功反序列化,需要修改序列化方式解決該問題: client.undo.logSerialization=kryo

修改完所有配置運行從官網下載的nacos-config.sh檔案將文本內容上次到nacos配置中心中:

# -h ip -p 埠 -t 命名空間 -g 分組
sh nacos-config.sh -h localhost -p 8848 -t 7e3699fa-09eb-4d47-8967-60f6c98da94a -g EXAMPLE-GROUP

部署好組態檔之后在Nacos命名空間為7e3699fa-09eb-4d47-8967-60f6c98da94a(dev)的配置管理界面可以看到文本中的內容,

Seata資料庫

按照config.txt中對應的資料庫連接資訊創建Seata資料庫并且創建以下幾張表

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;
部署Seata Server

以上作業準備就緒,進入bin目錄運行seata-server.bat(windows用戶)/seata-server.sh(linux用戶)即可,

Seata應用場景模擬

這里做一個用戶服務用戶登錄成功后呼叫會員服務增加會員積分場景案例,

父工程改造

工程名稱:spring-cloud-alibaba-version-parent,增加mybatis,seata序列化等依賴版本管理,

<!-- properties 增加版本號 -->
<!-- mybatis -->
<mybatis.plus.version>3.4.2</mybatis.plus.version>
<mybatis.plus.ds.version>2.5.4</mybatis.plus.ds.version>
<seata.serializer.kryo.version>1.3.0</seata.serializer.kryo.version>

<!-- dependencyManagement 增加以下依賴 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis.plus.version}</version>
</dependency>
<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-serializer-kryo</artifactId>
    <version>${seata.serializer.kryo.version}</version>
</dependency>
會員服務工程改造

工程名稱:spring-cloud-alibaba-service-member,增加資料庫與Seata依賴,增加用戶會員積分介面,

pom.xml

 <!-- Seata  & mybatis-plus -->
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
	<groupId>io.seata</groupId>
	<artifactId>seata-serializer-kryo</artifactId>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

bootstrap.yaml

#注意,此處省略之前配置的資訊....
#注意,此處省略之前配置的資訊....
#注意,此處省略之前配置的資訊....
#注意,此處省略之前配置的資訊....
#資料庫資訊配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/member_db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456
#Seata配置
seata:
  enabled: true
  application-id: ${spring.application.name}
  #對應nacos配置 service.vgroupMapping.my_test_tx_group
  tx-service-group: 'my_test_tx_group'
  service:
    vgroup-mapping:
      #對應nacos配置 service.vgroupMapping.my_test_tx_group 的值 default
      my_test_tx_group: 'default'
  registry:
    type: nacos
    nacos:
      server-addr: ${spring.cloud.nacos.discovery.server-addr}
      namespace: ${spring.cloud.nacos.discovery.namespace}
      group: ${spring.cloud.nacos.discovery.group}
      #cluster: ${spring.cloud.nacos.discovery.cluster}
  config:
    type: nacos
    nacos:
      server-addr: ${spring.cloud.nacos.discovery.server-addr}
      namespace: ${spring.cloud.nacos.discovery.namespace}
      group: ${spring.cloud.nacos.discovery.group}

注意事項:

  1. bootstrap.yaml中seata.tx-service-group 配置項一定要配置nacos配置中心中service.vgroupMapping對應的my_test_tx_group,也就是說一定要保持一致,
  2. bootstrap.yaml中seata.service.vgroup-mapping.my_test_tx_group配置項一定要配置nacos配置中心對應service.vgroupMapping.my_test_tx_group配置祥的值,

如果沒有注意上方兩點將會導致啟動時報:no available service 'default' found, please make sure registry config correct,

創建member_db資料庫

其中undo_log表為Seata回滾日志表,需要在每個使用到Seata的業務服務資料庫中都需要創建,

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_member_integral
-- ----------------------------
DROP TABLE IF EXISTS `t_member_integral`;
CREATE TABLE `t_member_integral`  (
  `ID` bigint(20) NOT NULL COMMENT '主鍵',
  `USERNAME` varchar(55) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '用戶名稱',
  `INTEGRAL` int(11) DEFAULT NULL COMMENT '積分',
  `CREDATE` datetime(0) DEFAULT NULL COMMENT '時間',
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for 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) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime(0) NOT NULL,
  `log_modified` datetime(0) NOT NULL,
  `ext` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

新增會員積分CRUD

我這里新增以下類,具體內容大家都比較熟悉,

MemberIntegralController.java
IMemberIntegralBiz.java
IMemberIntegralBizImpl.java
MemberIntegralMapper.java
MemberIntegral.xml

在這里所有增加會員積分的邏輯都寫在同一個類中 MemberIntegralController.java

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.gitee.eample.member.service.biz.IMemberIntegralBiz;
import com.gitee.eample.member.service.domain.MemberIntegral;
import com.gtiee.example.common.exception.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 用戶積分
 *
 * @author wentao.wu
 */
@RestController
@RequestMapping("/member/integral")
public class MemberIntegralController {
    @Autowired
    private IMemberIntegralBiz memberIntegralBiz;

    @PostMapping("/login/{username}")
    public Response<Boolean> login(@PathVariable("username") String username) {
        // 每天第一次登錄則增加積分,我這里就不判斷了,每次呼叫都新增一潭訓分記錄了
        MemberIntegral memberIntegral = new MemberIntegral();
        memberIntegral.setId(IdWorker.getId());
        memberIntegral.setIntegral(10);//固定10積分
        memberIntegral.setUsername(username);
        memberIntegral.setCredate(new Date());
        memberIntegralBiz.save(memberIntegral);
        return Response.createOk("登錄新增會員積分成功!", true);
    }
}

運行MemberServiceApplication.java啟動服務,如果想知道有沒有注冊成功:

第一可以看Seata Server端有沒有日志輸出,該日志內容主要為注冊的業務服務的資料庫資訊,

第二可以看業務服務有沒有輸出以下日志,有輸出以下日志則Seata Server端注冊成功

2021-11-05 09:56:30.962  INFO 16420 --- [           main] i.s.c.r.netty.NettyClientChannelManager  : will connect to 2.0.4.58:8091
2021-11-05 09:56:30.962  INFO 16420 --- [           main] i.s.c.rpc.netty.RmNettyRemotingClient    : RM will register :jdbc:mysql://localhost:3306/member_db
2021-11-05 09:56:30.967  INFO 16420 --- [           main] i.s.core.rpc.netty.NettyPoolableFactory  : NettyPool create channel to transactionRole:RMROLE,address:2.0.4.58:8091,msg:< RegisterRMRequest{resourceIds='jdbc:mysql://localhost:3306/member_db', applicationId='service-member', transactionServiceGroup='my_test_tx_group'} >
用戶服務工程改造

工程名稱:spring-cloud-alibaba-service-member,增加資料庫與Seata依賴,增加用戶登錄介面,增加呼叫會員服務積分介面feign,

由于內容一致此處省略pom.xml,bootstrap.xml(里面注意資料庫要修改為用戶服務的資料庫),

創建user_db資料庫

其中undo_log表為Seata回滾日志表,需要在每個使用到Seata的業務服務資料庫中都需要創建,


SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `ID` bigint(20) NOT NULL COMMENT '主鍵',
  `USERNAME` varchar(55) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '用戶名',
  `PWD` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '密碼',
  `ADDR` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '地址',
  `LAST_LOGIN_DATE` datetime(0) DEFAULT NULL COMMENT '最后登錄時間',
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, 'test1', '123456', '123', NULL);

-- ----------------------------
-- Table structure for 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) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime(0) NOT NULL,
  `log_modified` datetime(0) NOT NULL,
  `ext` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

新增用戶登錄CRUD

我這里新增以下類,具體內容大家都比較熟悉,

UserController.java
IUserBiz.java
IUserBizImpl.java
UserMapper.java
UserMapper.xml
MemberInfoControllerClient.java

MemberInfoControllerClient.java

/**
 * service-member服務遠程呼叫介面
 *
 * @author wentao.wu
 */
@FeignClient(name = "service-member")
public interface MemberInfoControllerClient {
    /**
     * 登錄送積分
     *
     * @param username
     * @return
     */
    @PostMapping("/member/integral/login/{username}")
    Response<Boolean> login(@PathVariable("username")String username);
}

IUserBiz.java

public interface IUserBiz extends IService<User> {
    /**
     * 用戶登錄并且贈送第一次登錄積分
     *
     * @param command
     * @return
     */
    boolean login(UserLoginCommand command);

}

IUserBizImpl.java

package com.gitee.eample.user.service.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.eample.user.service.controller.command.UserLoginCommand;
import com.gitee.eample.user.service.dao.UserMapper;
import com.gitee.eample.user.service.domain.User;
import com.gitee.eample.user.service.feign.MemberInfoControllerClient;
import com.gtiee.example.common.exception.Response;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Service
public class IUserBizImpl extends ServiceImpl<UserMapper, User> implements IUserBiz {

    @Autowired
    private MemberInfoControllerClient client;

    @GlobalTransactional(name = "login_add_member_intergral",rollbackFor = Exception.class)//開啟分布式事務
    @Override
    public boolean login(UserLoginCommand command) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, command.getUsername())
                .eq(User::getPwd, command.getPwd());
        User loginUser = getOne(wrapper);
        if (ObjectUtils.isEmpty(loginUser)) {
            return false;
        }
        //呼叫會員登錄介面增加積分
        Response<Boolean> response = client.login(command.getUsername());
        if (response.isOk()) {//增加積分成功,或已增加積分
            //呼叫積分介面成功,修改當前用戶登錄時間
            loginUser.setLastLoginDate(new Date());
            updateById(loginUser);
            //假設此處發生例外,不但修改當前用戶登錄時間需要回滾并且新增的會員積分資訊也回滾才算正常
            int i = 0 / 0;
            return true;
        } else {
            //增加積分失敗
            return false;
        }
    }
}

UserController.java

import com.gitee.eample.user.service.biz.IUserBiz;
import com.gitee.eample.user.service.controller.command.UserLoginCommand;
import com.gtiee.example.common.exception.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * User Business Controller
 *
 * @author wentao.wu
 */
@RestController
@RequestMapping("/users/")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserBiz userBiz;

    @PostMapping("/login")
    public Response<Boolean> login(UserLoginCommand command) {
        try {
            boolean result = userBiz.login(command);
            if (result) {
                return Response.createOk("登錄并贈送積分成功!", result);
            }else{
                return Response.createError("賬號或密碼不存在!", result);
            }
        } catch (Exception e) {
            logger.error("登錄失敗!", e);
            return Response.createError("服務器繁忙請稍后再試!", false);
        }
    }

}

運行啟動類UserServiceApplication.java,

服務改造成功后主要模擬有三個場景:

  1. 有分布式事務處理發生例外場景:呼叫積分介面成功,修改當前用戶登錄時間之后發生例外,用戶表的修改操作進行回滾,同時會員服務新增的用戶對應的積分資料同樣發生回滾
  2. 無分布式事務處理發生例外場景: 呼叫積分介面成功,修改當前用戶登錄時間之后發生例外,用戶表的修改操作進行回滾,用戶會員新增的資料并沒有發生回滾,此處造成資料例外,
  3. 正常執行場景: 呼叫積分介面成功,修改當前用戶登錄時間之后未發生例外,所有操作生效,
有分布式事務處理發生例外場景

IUserBizImpl.java中login方法增加分布式事務注解 @GlobalTransactional(name = "login_add_member_intergral",rollbackFor = Exception.class)//開啟分布式事務,name為屬性名稱,rollbackFor 為指定回滾例外,

首先在用戶服務表中插入一條用戶資料,作為登錄用戶:

INSERT INTO `user_db`.`t_user`(`ID`, `USERNAME`, `PWD`, `ADDR`, `LAST_LOGIN_DATE`) VALUES (1, 'test1', '123456', '123', NULL);

并且當前會員服務t_member_integral表中還沒有資料還沒初始化過資料,當前場景操作會修改t_user.LAST_LOGIN_DATE,并且向t_member_integral表中插入資料;但是最后發生例外導致操作失敗,并且存在分布式事務注解,此時會回滾所有服務DML操作,

請求用戶登錄介面:

請求成功后查看t_user與t_member_integral依舊沒有發生任何改變:

表示分布式事務處理成功無任何例外,

無分布式事務處理發生例外場景

IUserBizImpl.java中login方法注釋掉全域事務(分布式事務),并且修改為本地事務:

//@GlobalTransactional(name = "login_add_member_intergral",rollbackFor = Exception.class)//開啟分布式事務
@Transactional

請求用戶登錄介面:

此時發生的例外導致了用戶服務中修改LAST_LOGIN_DATE操作被回滾成功,但是t_member_integral表中依然插入了積分資料并未被回滾:

表示在跨服務呼叫下沒有分布式事務將會導致資料不一致,事務例外,

正常執行場景

IUserBizImpl.java中login方法注釋掉本地事務,并且修改為全域事務(分布式事務),這里改不改無所謂,事務都是成功的,無論使用本地事務與全域事務都不會有問題,此處改成全域事務主要是驗證全域事務不會影響什么:

@GlobalTransactional(name = "login_add_member_intergral",rollbackFor = Exception.class)//開啟分布式事務
//@Transactional

同時將login方法中的例外處理去除掉:

//假設此處發生例外,不但修改當前用戶登錄時間需要回滾并且新增的會員積分資訊也回滾才算正常
int i = 0 / 0;

請求用戶登錄介面,此時所有操作全部成功,用戶服務修改LAST_LOGIN_DATE成功,并且t_member_integral表中資料新增成功;這里就不貼圖了,浪費大家流量,

總結

  • 每個業務服務對應的資料庫中都需要包含undo_log表,這個表主要是記錄全域事務操作的日志,后續發生例外Seata會通過該日志進行事務回滾補償;
  • Seata回滾反序列化時Date型別無法反序列化,所以要修改Seata的序列化為:kryo;(此問題將在1.5版本 Seata發布后徹底解決)

原始碼代碼存放地址

gitee: https://gitee.com/SimpleWu/spring-cloud-alibaba-example.git
cnblogs: https://www.cnblogs.com/SimpleWu
持續更新目錄:https://www.cnblogs.com/SimpleWu/p/15476427.html

學習是永無止境的,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/354449.html

標籤:其他

上一篇:windows系統下使用java語言,在mysql資料庫中做定時資料備份、洗掉

下一篇:Python爬蟲超詳細講解,零基礎入門,老年人都看得懂

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more