🔍 登录 注册

MySQL的分布式事务解决方案

大 大苹果 2024-07-12 linux 👁 44 ⏱ 10min

分布式事务是在多个不同的数据源或数据库节点上执行的事务,并且需要保证这些事务具有原子性、一致性、隔离性和持久性(ACID特性)。在基于MySQL的系统中,常见的分布式事务解决方案包括两阶段提交协议(2PC)、三阶段提交协议(3PC)、基于消息中间件的事务(如RocketMQ事务消息),以及TCC(Try-Confirm-Cancel)等。下面是一个基于MySQL的分布式事务解决方案的详细介绍和实现:

1. 两阶段提交协议(2PC)

概念

两阶段提交协议(2PC)是一种经典的分布式事务处理协议,分为两个阶段:准备阶段和提交阶段。

  • 准备阶段:协调者向所有参与者发送请求,询问他们是否可以提交事务,并等待所有参与者的回复。
  • 提交阶段:如果所有参与者都同意提交事务,协调者向所有参与者发送提交请求;如果有任何一个参与者不同意提交,协调者向所有参与者发送回滚请求。

实现步骤

  1. 初始化项目并安装依赖:
mkdir distributed-tx-example
cd distributed-tx-example
npm init -y
npm install mysql2 express body-parser
  1. 创建数据库和表:
-- 数据库1:db1
CREATE DATABASE db1;
USE db1;
CREATE TABLE accounts (
    id INT PRIMARY KEY AUTO_INCREMENT,
    balance DECIMAL(10, 2) NOT NULL
);

-- 数据库2:db2
CREATE DATABASE db2;
USE db2;
CREATE TABLE transactions (
    id INT PRIMARY KEY AUTO_INCREMENT,
    account_id INT NOT NULL,
    amount DECIMAL(10, 2) NOT NULL,
    status ENUM('PENDING', 'COMMITTED', 'ROLLED_BACK') NOT NULL
);
  1. 实现两阶段提交协议:

在server.js中实现两阶段提交协议:

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2/promise');

const app = express();
app.use(bodyParser.json());

const db1 = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'db1',
});

const db2 = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'db2',
});

app.post('/transfer', async (req, res) => {
    const { fromAccountId, toAccountId, amount } = req.body;

    const conn1 = await db1.getConnection();
    const conn2 = await db2.getConnection();

    try {
        await conn1.beginTransaction();
        await conn2.beginTransaction();

        const [fromAccount] = await conn1.query('SELECT balance FROM accounts WHERE id = ?', [fromAccountId]);
        if (fromAccount[0].balance < amount) {
            throw new Error('Insufficient funds');
        }

        await conn1.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, fromAccountId]);
        await conn2.query('INSERT INTO transactions (account_id, amount, status) VALUES (?, ?, ?)', [toAccountId, amount, 'PENDING']);

        await conn1.commit();
        await conn2.commit();

        // 第二阶段提交
        await conn2.query('UPDATE transactions SET status = ? WHERE account_id = ? AND amount = ?', ['COMMITTED', toAccountId, amount]);

        res.json({ message: 'Transfer successful' });
    } catch (error) {
        await conn1.rollback();
        await conn2.rollback();

        // 第二阶段回滚
        await conn2.query('UPDATE transactions SET status = ? WHERE account_id = ? AND amount = ?', ['ROLLED_BACK', toAccountId, amount]);

        res.status(500).json({ message: 'Transfer failed', error: error.message });
    } finally {
        conn1.release();
        conn2.release();
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

运行和测试

启动服务器并测试转账API:

node server.js

使用Postman或curl测试转账API:

curl -X POST http://localhost:3000/transfer -H "Content-Type: application/json" -d '{"fromAccountId": 1, "toAccountId": 2, "amount": 100.00}'

2. TCC(Try-Confirm-Cancel)模式

TCC(Try-Confirm-Cancel)是一种柔性事务模型,通过将业务操作拆分为三个步骤来保证分布式事务的最终一致性:

  1. Try:尝试执行业务操作,预留资源。
  2. Confirm:确认业务操作,真正执行操作。
  3. Cancel:取消业务操作,释放预留资源。

实现步骤

假设我们有两个服务,一个处理账户操作,另一个处理交易记录。

  1. 账户服务:负责处理账户余额的预留和确认。
  2. 交易服务:负责记录交易并确认交易状态。
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2/promise');

const app = express();
app.use(bodyParser.json());

const accountDb = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'db1',
});

const transactionDb = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'db2',
});

// 账户服务
app.post('/account/try', async (req, res) => {
    const { accountId, amount } = req.body;

    const conn = await accountDb.getConnection();
    try {
        await conn.beginTransaction();

        const [account] = await conn.query('SELECT balance FROM accounts WHERE id = ?', [accountId]);
        if (account[0].balance < amount) {
            throw new Error('Insufficient funds');
        }

        await conn.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, accountId]);

        await conn.commit();
        res.json({ message: 'Try successful' });
    } catch (error) {
        await conn.rollback();
        res.status(500).json({ message: 'Try failed', error: error.message });
    } finally {
        conn.release();
    }
});

app.post('/account/confirm', async (req, res) => {
    const { accountId, amount } = req.body;

    // 确认操作逻辑

    res.json({ message: 'Confirm successful' });
});

app.post('/account/cancel', async (req, res) => {
    const { accountId, amount } = req.body;

    const conn = await accountDb.getConnection();
    try {
        await conn.beginTransaction();

        await conn.query('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, accountId]);

        await conn.commit();
        res.json({ message: 'Cancel successful' });
    } catch (error) {
        await conn.rollback();
        res.status(500).json({ message: 'Cancel failed', error: error.message });
    } finally {
        conn.release();
    }
});

// 交易服务
app.post('/transaction/try', async (req, res) => {
    const { transactionId, accountId, amount } = req.body;

    const conn = await transactionDb.getConnection();
    try {
        await conn.beginTransaction();

        await conn.query('INSERT INTO transactions (id, account_id, amount, status) VALUES (?, ?, ?, ?)', [transactionId, accountId, amount, 'PENDING']);

        await conn.commit();
        res.json({ message: 'Try successful' });
    } catch (error) {
        await conn.rollback();
        res.status(500).json({ message: 'Try failed', error: error.message });
    } finally {
        conn.release();
    }
});

app.post('/transaction/confirm', async (req, res) => {
    const { transactionId } = req.body;

    const conn = await transactionDb.getConnection();
    try {
        await conn.beginTransaction();

        await conn.query('UPDATE transactions SET status = ? WHERE id = ?', ['COMMITTED', transactionId]);

        await conn.commit();
        res.json({ message: 'Confirm successful' });
    } catch (error) {
        await conn.rollback();
        res.status(500).json({ message: 'Confirm failed', error: error.message });
    } finally {
        conn.release();
    }
});

app.post('/transaction/cancel', async (req, res) => {
    const { transactionId } = req.body;

    const conn = await transactionDb.getConnection();
    try {
        await conn.beginTransaction();

        await conn.query('UPDATE transactions SET status = ? WHERE id = ?', ['ROLLED_BACK', transactionId]);

        await conn.commit();
        res.json({ message: 'Cancel successful' });
    } catch (error) {
        await conn.rollback();
        res.status(500).json({ message: 'Cancel failed', error: error.message });
    } finally {
        conn.release();
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

运行和测试

启动

读完了?给作者一点支持

本文采用 CC BY 4.0 协议转载 · © 大苹果

评论(0)

登录 后参与评论。

  • 还没有评论,来抢沙发。

🔗 相关文章

Mysql 表被标记为崩溃,最后一次自动化修复失败

当 MySQL 日志中出现“表被标记为崩溃且自动修复失败”的提示时,通常表示 MySQL 在启动过程中检测到某个表的文件系统或存储引擎层出现了问题。这种情况通常会导致表无法正常使用,需要手动进行修复。以下是处理这种情况的一些步骤和方法: ### 1. **查看具体错误信息** 首先,需要查看 MySQL 错误日志以获取更多的错误信息。这可以帮助确定崩溃的表和具体的问题。 ```bash # 查看 MySQL 错误日志 tail -f /var/log/mysql/error.log ``` ### 2. **修复表** 不同的存储引擎有不同的修复工具,以下是常用的修复方法: #### **使用 `myisamchk` 修复 MyISAM 表** 如果崩溃的表使用的是 MyISAM 存储引擎,可以使用 `myisamchk` 工具来修复表。 1. 停止 MySQL 服务: ```bash sudo systemctl stop mysql ``` 2. 使用 `myisamchk` 修复表:

2024/8/11👍 0

mermaid.min.js的使用及介绍

`mermaid.min.js` 是一个 JavaScript 库,用于在浏览器中轻松绘制复杂的图表和流程图。Mermaid 通过使用简单的标记语言来描述图表,使得用户无需深入学习图表绘制的底层技术即可创建专业的图形。 在这篇文章中,我们将介绍 `mermaid.min.js` 的功能、应用场景、如何在项目中使用,以及一些常用的示例。 ## Mermaid 的功能 Mermaid 支持多种类型的图表,包括但不限于: 1. **流程图(Flowchart)**: - 用于表示流程或过程中的步骤。 - 支持各种节点和连线风格。 2. **序列图(Sequence Diagram)**: - 用于表示对象之间的交互。 - 展示消息的发送和接收过程。 3. **类图(Class Diagram)**: - 用于表示类及其关系。 - 支持类的属性和方法定义。 4. **状态图(State Diagram)**: - 用于描述系统状态及其转换。 - 适用于复杂的状态机建模。 5. **甘

2024/8/9👍 0

docker之Dockerfile及docker compose配置文件的说明及使用

Docker 的配置文件对于镜像构建和容器化应用的管理至关重要。在 Docker 中,主要的配置文件是 Dockerfile 和 docker-compose.yml。Dockerfile 用于构建镜像,而 docker-compose.yml 用于定义多容器应用。下面将详细介绍这两个文件的配置选项和用法。 ## Dockerfile 配置详解 **Dockerfile** 是一个文本文件,其中包含一组指令,用于定义如何构建 Docker 镜像。以下是 Dockerfile 中常用的指令及其用法: ### FROM `FROM` 指令用于指定基础镜像,是 Dockerfile 中的第一条指令。 ```dockerfile FROM node:14 ``` 上例中,`node:14` 是官方的 Node.js 版本 14 的镜像。 ### LABEL `LABEL` 用于为镜像添加元数据,以键值对形式存在。 ```dockerfile LABEL maintainer="your-email@example.com" LABE

2024/8/9👍 0