Java分布式事务(七)

news/2024/4/29 3:15:40/文章来源:https://blog.csdn.net/Wwd631255/article/details/129527029

文章目录

    • 🔥Seata提供XA模式实现分布式事务_业务说明
    • 🔥Seata提供XA模式实现分布式事务_下载启动Seata服务
    • 🔥Seata提供XA模式实现分布式事务_搭建聚合父工程构建
    • 🔥Seata提供XA模式实现分布式事务_转账功能实现上
    • 🔥Seata提供XA模式实现分布式事务_转账功能实现下

🔥Seata提供XA模式实现分布式事务_业务说明

在这里插入图片描述

业务说明
本实例通过Seata中间件实现分布式事务,模拟两个账户的转账交易
过程。两个账户在两个不同的银行(张三在bank1、李四在bank2),bank1和bank2是两个微服务。交易过程中,张三给李四转账制定金额。上述交易步骤,要么一起成功,要么一起失败,必须是一个整体性的事务。
在这里插入图片描述
工程环境

服务名称服务版本
数据库MySQL-5.7.25
JDK1.8
微服务框架Spring-boot-2.6.3、Spring-Cloud-2021.0.0、Spring-Cloud-Alibaba-2021.0.1.0
Seata客户端(RM、TM)Spring-cloud-alibaba-seata-2021.0.1.0
Seata服务端(TC)Seata-server-1.4.2
服务注册Nacos
Mybatis plus3.5.1

创建数据库
bank1库,包含张三账户

CREATE DATABASE /*!32312 IF NOT EXISTS*/bank1;
/*!40100 DEFAULT CHARACTER SET utf8 */;
USE bank1;
/*Table structure for table account_info */
DROP TABLE IF EXISTS account_info;
CREATE TABLE account_info (id bigint(20) NOT NULL AUTO_INCREMENT,
account_name varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '户主姓名',
account_no varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '银行卡号',
account_password varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '帐户密码',account_balance double DEFAULT NULL COMMENT '帐户余额',
PRIMARY KEY (id) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULTCHARSET=utf8 COLLATE=utf8_bin
ROW_FORMAT=DYNAMIC;
/*Data for the table `account_info` */
insert  into
account_info(id,account_name,account_no ,account_password,account_balance) values
(2,'张三','1',NULL,1000);

bank2库,包含李四账户

CREATE DATABASE /*!32312 IF NOT EXISTS*/bank2
/*!40100 DEFAULT CHARACTER SET utf8 */;
USE bank2;
/*Table structure for table account_info */
DROP TABLE IF EXISTS account_info;
CREATE TABLE account_info (
id bigint(20) NOT NULL AUTO_INCREMENT,
account_name varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '户主姓名',
account_no varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '银行卡号',
account_password varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT '帐户密码', account_balance double DEFAULT NULL COMMENT  '帐户余额',
PRIMARY KEY (id) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT
CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=DYNAMIC;
/*Data for the table `account_info` */
insert  into account_info(id,account_name,account_no,account_password,account_balance) values(3,'李四','2',NULL,0);

🔥Seata提供XA模式实现分布式事务_下载启动Seata服务

在这里插入图片描述

下载seata服务器
下载地址:https://github.com/seata/seata/releases

在这里插入图片描述

解压并启动

tar -zxvf seata-server-1.4.2.tar.gz -C
/usr/local/
#后台运行
nohup sh seata-server.sh -p 9999 -h
192.168.66.100 -m file &> seata.log &

注意:
其中9999为服务端口号;file为启动模式,这里指seata服务将采用文件的方式存储信息。

测试
查看启动日志

cat seata.log

在这里插入图片描述

🔥Seata提供XA模式实现分布式事务_搭建聚合父工程构建

创建工程distribute-transaction
在这里插入图片描述

字符编码
在这里插入图片描述

注解生效激活
72

Java编译版本选择

 <!-- 指定JDK版本--><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin></plugins></build>

File Type过滤
在这里插入图片描述

pom配置版本

<properties><spring-boot.version>2.6.3</springboot.version><spring.cloud.version>2021.0.1</spring.cloud.version><spring.cloud.alibaba.version>2021.0.1.0</spring.cloud.alibaba.version><lombok.version>1.18.22</lombok.version></properties><dependencyManagement><dependencies><!--spring boot 2.6.3--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-bootstarter-parent</artifactId><version>${spring-boot.version}
</version><type>pom</type><scope>import</scope></dependency><!--       SpringCloud --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-clouddependencies</artifactId><version>${spring.cloud.version}</version><type>pom</type><scope>import</scope></dependency><!--     SpringCloud Aliabab  --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${spring.cloud.alibaba.version}
</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}
</version></dependency></dependencies></dependencyManagement>

IDEA开启Dashboard
普通的Run面板
在这里插入图片描述

Run Dashboard面板
在这里插入图片描述
修改配置文件
在.idea/workspace.xml 文件中找到

添加配置

<component name="RunDashboard"><option name="ruleStates"><list><RuleState><option name="name"
value="ConfigurationTypeDashboardGroupingRule"/></RuleState><RuleState><option name="name"
value="StatusDashboardGroupingRule" /></RuleState></list></option><option name="configurationTypes"><set><option value="SpringBootApplicationConfigurationType"/></set>
</option>
</component>

🔥Seata提供XA模式实现分布式事务_转账功能实现上

实现如下功能
⭐李四账户增加金额。

创建bank2
在这里插入图片描述
pom引入依赖

 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starterweb</artifactId></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-bootstarter</artifactId><version>3.5.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connectorjava</artifactId><version>5.1.49</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starteralibaba-nacos-discovery</artifactId></dependency>

编写主启动类

//添加对mapper包扫描 Mybatis-plus
@MapperScan("com.it.mapper")
@SpringBootApplication
@Slf4j
//开启发现注册
@EnableDiscoveryClient
public class SeataBank2Main6002 {public static void main(String[] args) {SpringApplication.run(SeataBank1Main6002.class
,args);log.info("**************
SeataBank1Main6002 *************");}
}

编写YML配置文件

server:port: 6002
spring:application:name: seata-bank2
cloud:nacos:discovery:# Nacos server地址server-addr: 192.168.66.101:8848datasource:url: jdbc:mysql://localhost:3306/bank2?
useUnicode=true&characterEncoding=utf-
8&useSSL=false&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driver   

代码生成

引入Mybatis Plus代码生成依赖

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plusgenerator</artifactId><version>3.5.2</version></dependency><!-- 模板引擎 --><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-enginecore</artifactId><version>2.0</version></dependency>

生成代码

package com.it.utils;
import
com.baomidou.mybatisplus.generator.FastAutoGenerator;
import
com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.Arrays;
import java.util.List;
public class CodeGenerator {public static void main(String[] args) {FastAutoGenerator.create("jdbc:mysql://192.168.66.100:3306/bank2", "root", "123456").globalConfig(builder -> {builder.author("it")
// 设置作者.commentDate("MM-dd") // 注释日期格式.outputDir(System.getProperty("user.dir")+
"/xa-seata/bank2"+ "/src/main/java/") // 指定输出目录.fileOverride(); // 覆盖文件})// 包配置.packageConfig(builder -> {
builder.parent("com.it") // 包名前缀.entity("entity")
//实体类包名.mapper("mapper")
//mapper接口包名.service("service"); //service包名}).strategyConfig(builder -> {// 设置需要生成的表名List<String> strings =
Arrays.asList("account_info");builder.addInclude(strings)
// 开始实体类配置
.entityBuilder()
// 开启lombok模型
.enableLombok()
//表名下划线转驼峰
.naming(NamingStrategy.underline_to_camel)
//列名下划线转驼峰
.columnNaming(NamingStrategy.underline_to_camel
);}).execute();}
}               

编写转账接口

public interface IAccountInfoService {//李四增加金额void updateAccountBalance(String accountNo,Double amount);
}

编写转账接口实现类

@Service
@Slf4j
public class AccountInfoServiceImpl implements IAccountInfoService {@AutowiredAccountMapper accountMapper;@Overridepublic void updateAccountBalance(String
accountNo, Double amount) {// 1. 获取用户信息AccountInfo accountInfo =
accountMapper.selectById(accountNo);accountInfo.setAccountBalance(accountInfo.getAccountBalance() + amount);accountMapper.updateById(accountInfo);}
}

编写控制层

@RestController
@RequestMapping("/bank2")
public class Bank2Controller {@AutowiredIAccountInfoService accountInfoService;//接收张三的转账@GetMapping("/transfer")public String transfer(Double amount){//李四增加金额accountInfoService.updateAccountBalance("3",amount);return "bank2"+amount;}
}

🔥Seata提供XA模式实现分布式事务_转账功能实现下

实现如下功能
⭐张三账户减少金额
⭐远程调用bank2向李四转账。

pom引入依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-bootstarter</artifactId><version>3.5.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connectorjava</artifactId><version>5.1.49</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starteralibaba-nacos-discovery</artifactId></dependency><!-- openfeign --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starteropenfeign</artifactId></dependency><dependency> 
<groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starterloadbalancer</artifactId></dependency>             

编写主启动类

//添加对mapper包扫描 Mybatis-plus
@MapperScan("com.it.mapper")
//开启OpenFiegn
@EnableFeignClients
@SpringBootApplication
@Slf4j
//开启发现注册
@EnableDiscoveryClient
public class SeataBank1Main6001 {public static void main(String[] args) {SpringApplication.run(SeataBank1Main6001.class,args);log.info("**************
SeataBank1Main6001 *************");}
}

编写YML配置文件

server:port: 6001
spring:application:name: seata-bank1cloud:nacos:discovery:# Nacos server地址server-addr: 192.168.66.101:8848datasource:url: jdbc:mysql://localhost:3306/bank1?
useUnicode=true&characterEncoding=utf-
8&useSSL=true&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driver

创建实体类

@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName("account_info")
@Data
public class AccountInfo {//id@TableIdprivate Long id;//户主姓名@TableField("account_name")private String accountName;//银行卡号@TableField("account_no")private String accountNo;//账户密码@TableField("account_password")private String accountPassword;//账户余额@TableField("account_balance")private Double accountBalance;
}   

编写持久层

@Component
@Mapper
public interface AccountMapper extends
BaseMapper<AccountInfo> {
}

编写转账接口

public interface IAccountInfoService {//张三扣减金额public void updateAccountBalance(String
accountNo, Double amount);
}

编写远程调用接口

@Component
@FeignClient(value="seata-bank2")
public interface Bank2Client {//远程调用李四的微服务@GetMapping("/bank2/transfer")String transfer(@RequestParam("amount")
Double amount);
}

编写转账接口实现类

@Service
@Slf4j
public class AccountInfoServiceImpl implements IAccountInfoService {@AutowiredAccountMapper accountMapper;@AutowiredBank2Client bank2Client;@Overridepublic void updateAccountBalance(String
accountNo, Double amount) {// 1. 获取用户信息AccountInfo accountInfo =
accountMapper.selectById(2);// 2. 判断张三账户余额是否有钱if (accountInfo.getAccountBalance() >
amount){//扣减张三的金额accountInfo.setAccountBalance(accountInfo.getAccountBalance()-amount);int result =
accountMapper.updateById(accountInfo);if (result!=0){//调用李四微服务,转账bank2Client.transfer(amount);}}}
}

编写控制层

@RestController
public class Bank1Controller {@AutowiredIAccountInfoService IAccountInfoService;//张三转账@GetMapping("/transfer")public String transfer(Double amount){IAccountInfoService.updateAccountBalance("1",amount);return "bank1"+amount;}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_274010.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

考研复试7 汇编语言、编程语言

一、寄存器 1. 寄存器概述 &#xff08;1&#xff09;典型的CPU包括器件 运算器控制器总线&#xff1a;内部总线实现CPU内部各个器件之间的联系&#xff1b;外部总线实现CPU和主板上其它器件的联系。 &#xff08;2&#xff09;8086CPU有14个寄存器&#xff0c;它们的名称为…

git查漏补缺之 stash

git查漏补缺之 stash Start 最近在工作的过程中&#xff0c;遇到 git 中的stash 暂存这个命令&#xff0c;感觉非常有用&#xff0c;写一个博客记录一下。 1. stash 首先第一个就是 stash &#xff0c;英译过来的意思就是 存放/贮藏。 主要的使用场景&#xff1a; 我正在…

最好用的Markdown编辑器:MWeb Pro mac

MWeb pro Mac中文版是一款非常好用的Markdown编辑器和博客生成工具&#xff0c;支持语法高亮&#xff0c;预览&#xff0c;Fenced code blocks和代码高亮&#xff0c;Math ML支持&#xff0c;具有导出HTML/PDF&#xff0c;自定编辑器主题&#xff0c;字数统计&#xff0c;大纲视…

Linux--MySQL数据库的基本概念、编译安装以及MySQL数据库自动补全功能的实现

文章目录一.数据库的基本概念1、数据&#xff08;Data&#xff09;2、表3、数据库4、数据库管理系统&#xff08;DBMS&#xff09;5、数据库系统6、访问数据库的流程二.数据库系统发展史1、第一代数据库2、第二代数据库3、第三代数据库三、当今主流数据库介绍1、SQL Server (微…

电商出海:阿里、拼多多“快马扬鞭”

配图来自Canva可画 经过多年的发展&#xff0c;电商已经逐渐深入人们的日常生活中了&#xff0c;人们也愈发习惯使用电商平台了。得益于消费者需求的持续增长&#xff0c;电商行业的体量规模也在持续扩大&#xff0c;行业内也涌现出了诸多电商平台&#xff0c;比如淘宝、京东、…

error: C1083: 无法打开包括文件: “QtGui/QApplication”: No such file or directory

Qt系列文章目录 文章目录Qt系列文章目录前言一、原因二、解决办法1.修改pro工程文件2.在main.cpp中三、总结前言 当我们从网上或者从打开别人的工程师&#xff0c;报错&#xff0c;C1083: 无法打开包括文件: “QtGui/QApplication”。 原因&#xff1a;Qt5里不再用QtGui模块&a…

docker 安装 nginx无坑版

一. 拉取镜像 docker pull nginx二. 创建挂载目录 mkdir -p /usr/local/nginx/conf mkdir -p /usr/local/nginx/log mkdir -p /usr/local/nginx/html三. 从nginx容器里复制nginx的配置文件到主机里 创建个容器 docker run --name nginx -p 80:80 -d nginx将容器内的配置文件…

mysql之窗口函数练习

&#x1f34a;今天复习一下mysql中的窗口函数&#xff0c;主要是通过几道练习题复习和加深一下对窗口函数的理解&#xff0c;对往期内容感兴趣的同学可以参考如下内容&#x1f447;: 链接: 牛客SQL大厂真题——某音短视频.链接: 京东数据分析SQL面试题.链接: 百度用户增长SQL面…

Java实习生------MySQL10道面试题打卡

今日语录&#xff1a;“没有执行力&#xff0c;就没有竞争力 ”&#x1f339; 参考资料&#xff1a;图解MySQL、MySQL面试题 1、事务有哪些特性&#xff1f; 原子性&#xff1a; 一个事务中的所有操作&#xff0c;要么全部完成&#xff0c;要么全部不完成&#xff0c;不会出现…

Linux系统的安装以及参数配置 -- VMware(虚拟机)安装--ubuntu 20.04--VMware Tools工具安装

Linux系统的安装以及参数配置 PS&#xff1a;本文章为上课后整理笔记&#xff0c;作为以后学习工作的学习使用&#xff0c;也作为一次课程记录 一、Linux系统的安装常用方法 – 3种 1.直接Linux操作替换Windows – 专业Linux开发者 – 接受Linux相关软件的使用 2.安装双系统…

诗佛王维,眼前的苟且和远方的田野?

转自&#xff1a;媲美李白杜甫的诗人&#xff0c;他的人生可以复制_百科TA说 (baidu.com)他受到的羁绊&#xff0c;他做出的选择&#xff0c;提供了一种温润平和的过日子模式。大部分人无法决绝地脱离社会&#xff0c;隐遁起来&#xff0c;也无法在社会中不计底线&#xff0c;混…

JavaScript性能优化小窍门汇总(含实例)

在众多语言中&#xff0c;JavaScript已经占有重要的一席之地&#xff0c;利用JavaScript我们可以做很多事情 &#xff0c; 应用广泛。在web应用项目中&#xff0c;需要大量JavaScript的代码&#xff0c;将来也会越来越多。但是由于JavaScript是一个作为解释执行的语言&#xff…

Vue|样式绑定

class 与 style 是 HTML 元素的属性&#xff0c;用于设置元素的样式&#xff0c;我们可以用 v-bind 来设置样式属性。Vue.js v-bind 在处理 class 和 style 时&#xff0c; 专门增强了它。表达式的结果类型除了字符串之外&#xff0c;还可以是对象或数组。 文末名片获取源码 精…

根据平均分来划分等级-课后程序(JavaScript前端开发案例教程-黑马程序员编著-第2章-课后作业)

【案例2-1】 根据平均分来划分等级 一、案例描述 考核知识点 switch语句 练习目标 掌握switch语句的使用。 需求分析 switch语句也是多分支语句&#xff0c;针对某个表达式的值做出判断&#xff0c;来决定执行哪一段代码&#xff0c;本案例用于实现根据输入的小明同学的5门课…

百度CTO王海峰:全栈AI技术加持,打造新一代大语言模型文心一言

3月16日&#xff0c;百度在北京总部召开新闻发布会&#xff0c;百度创始人、董事长兼首席执行官李彦宏和百度首席技术官王海峰出席&#xff0c;李彦宏展示了新一代知识增强大语言模型文心一言在文学创作、商业文案创作、数理逻辑推算、中文理解、多模态生成五个使用场景中的综合…

【linux】管道pipe(),dup()系统调用

int pipe(int p[2]) 函数作用&#xff1a;生成一个管道&#xff0c;将管道读端的文件标识符存到p[0]中&#xff0c;将管道写端的文件标识符存到p[1]中。返回值&#xff1a;若成功返回0&#xff0c;失败返回-1 管道的理解 如图&#xff0c;当创建完管道以后的父进程fork出两个子…

Python中模块是个啥

昨天有粉丝问我说&#xff0c;啥是模块&#xff1f;经常听别人口中提这个词&#xff0c;但就是不懂。 模块可以认为是一盒主题积木&#xff0c;通过它可以拼出某一主题的东西。这与之前介绍的函数不同&#xff0c;一个函数相当于一块积木&#xff0c;而一个模块中可以包括很多函…

【C++进阶】unordered_set和unordered_map的介绍及使用

文章目录unordered系列容器介绍unordered_setunordered_set的模板参数unordered_set的函数接口介绍unordered_set的重要接口的使用构造函数增删查迭代器的使用unordered_mapunordered_map的模板参数unordered_map的函数接口介绍unordered_map的重要接口的使用增删查改迭代器的使…

EMQ 南洋万邦云边一体化方案:激活数据潜力,打造智慧工业园区

在工业 4.0 的浪潮之中,全球制造业再度振兴和崛起,并经历着前所未有从流程驱动转向数据驱动的变革。 近年来,数智化绿色工厂正在成为制造业竞争力的主要驱动力,依托物联网、工业互联网,人工智能等先进制造技术的深度融合,智能工厂变得更高效、更灵活,拥有更高的交付韧性和成本…

解忧杂货铺(四):Hightec生成HEX方法+小功能开启

目录 1、概述 2、 4.6.6的生成方法 3 、HighTEC4.9.3的生成.hex方法 4、MAP文件生成方法 5、elf生成 6、编译优化 7、输出编译过程中的详细信息 8、快速定位内存 1、概述 本文章纯属整合&#xff0c;大部分属于外链&#xff0c;补充一下&#xff0c;后面是自己记录的了…