【Redis】In-depth understanding of Redis transaction mechanism


Preface

1. Review MySQL transactions

1.1 Concept and characteristics of MySQL transactions

MySQL transactions are a mechanism for managing database operations. It ensures that a set of related SQL operations either all execute successfully or all fail, thereby maintaining data consistency and integrity. Transaction is one of the core concepts in database management systems, which usually follows ACID properties:

  1. Atomicity: A transaction is an atomic operation, either all executions succeed or all fail. If any part of the operation fails, the entire transaction will be rolled back and the database state will remain unchanged.

  2. Consistency: The execution of a transaction moves the database from one consistent state to another consistent state. This means that after a transaction is executed, the database must satisfy pre-defined integrity constraints.

  3. Isolation: Isolation defines the degree of mutual influence between multiple concurrent transactions. Different isolation levels provide different degrees of isolation, including read uncommitted, read committed, repeatable read, and serialization levels.

  4. Durability: Once a transaction is committed, its results are permanently stored in the database and remain unchanged after system failures.

1.1 Management of MySQL transactions

In MySQL, you can use the following keywords to manage transactions:

  • BEGIN : Start a new transaction.
  • COMMIT : Commit the transaction and save the changes to the database.
  • ROLLBACK : Roll back the transaction and undo uncommitted changes.
  • SAVEPOINT : Creates a savepoint that can be rolled back at a specific point in the transaction.
  • SET TRANSACTION : Set transaction attributes, such as isolation level.

The following is a simple MySQL transaction example:

BEGIN;  -- 开始事务

-- 在事务中执行一些SQL操作
INSERT INTO users (id, username) VALUES (1, 'user1');
UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;

-- 如果一切正常,提交事务
COMMIT;

If an error occurs during transaction execution or the transaction needs to be canceled, you can use ROLLBACKthe command to roll back the transaction, which will undo all changes in the transaction.

BEGIN;  -- 开始事务

-- 在事务中执行一些SQL操作
INSERT INTO users (id, username) VALUES (2, 'user2');
-- 发生错误,回滚事务
ROLLBACK;

Using transactions can ensure the data integrity of the database, especially when multiple users access the database at the same time. Depending on specific application scenarios and requirements, different isolation levels can be selected to balance the needs between concurrency and consistency. In practical applications, the correct use of transactions is the key to ensuring data consistency and reliability.

2. Understanding of Redis transactions

2.1 What is a Redis transaction?

2.1.1 The concept of Redis transactions

Simply put, Redis transactions allow a set of Redis commands to be combined into a single, uninterruptible sequence of operations. This means that once a Redis transaction is started, any commands from other clients during the execution of the transaction will not interrupt the transaction, but will be queued for execution until the transaction is committed or canceled.

2.1.2 In-depth understanding of Redis transactions

  • The core concept of a Redis transaction involves creating a buffer called a buffer on the Redis server "事务队列". When a transaction is started, all commands related to the transaction will be queued into the queue in order. Only when a command to execute a transaction is sent, the commands in the queue are executed atomically one after another, ensuring that the set of commands either all succeed or all fail.

  • In the transaction queue, any number of Redis commands, including read and write operations, can be included to perform a series of complex operations. However, it is important to note that Redis transactions do not 不支持像传统数据库那样的隔离级别和回滚机制. Therefore, the application needs to handle errors and rollback logic on its own.

  • Transactions that have not received execution commands are queued in the Redis server 等待状态. Although the commands are sent to the server, they are not executed and will not affect the normal execution of other client commands.

In short, Redis transactions provide a method 将多个命令打包成一个原子操作的能力that is very useful when you need to ensure the consistency of a series of operations . However, it has some differences from traditional database transactions, especially in terms of isolation and durability.

2.2 Comparison of Redis transactions and MySQL transactions

Although both Redis and MySQL involve the concept of transactions, there are some key differences in implementation and application.

2.2.1 Transaction granularity

Redis Transactions: Redis transactions typically work at the granularity of a single command. Multiple Redis commands can be put into a transaction, but each command itself is indivisible. This allows performing a series of simple operations, but not complex transactions across multiple Redis commands.

MySQL Transactions: MySQL transactions have wider granularity, allowing complex transactions to be executed across multiple SQL statements, including the beginning and end of a transaction.

2.2.2 ACID properties

Redis transaction: Redis transaction supports atomicity (Atomicity) and consistency (Consistency) , ensuring that a set of commands either all succeed or all fail, and maintains data consistency after the transaction is executed. But Redis does not support isolation and durability in traditional databases.

MySQL transactions: MySQL transactions support complete ACID properties, including atomicity, consistency, isolation, and durability. This makes MySQL transactions very useful in applications that require strict transaction integrity, such as financial and e-commerce systems.

2.2.3 Concurrency control

Redis Transaction: Redis transaction is 单线程, only one transaction can be executed at a time. This limits concurrency because other clients' commands must 排队等待be executed. At the same time, Redis uses optimistic locking to control concurrency.

MySQL transaction: MySQL has a powerful concurrency control mechanism that supports 多个事务simultaneous execution. You can choose different isolation levels as needed to balance concurrency and consistency.

2.2.4 Error handling and rollback

Redis transactions: Redis transactions provide the ability to rollback operations. You can use DISCARDthe command to cancel the current transaction and clear queued commands. But Redis will not automatically roll back erroneous commands in transactions.

MySQL transaction: MySQL transaction supports explicit rollback operation, which can be used ROLLBACKto undo the commands in the executed transaction and restore to the state before the transaction started.

2.2.5 Application scenarios

Redis transactions: Redis transactions are often used for specific use cases such as caches, queues, counters, etc., where simple atomic operations are required but strict isolation and durability are not emphasized .

MySQL transaction: MySQL transaction is widely used in applications that support transaction integrity, such as e-commerce, financial systems , etc. These applications require strong ACID support.

In short, there are important differences between Redis transactions and MySQL transactions in terms of granularity, ACID properties, concurrency control, error handling, and application scenarios. Choosing which type of transaction to use depends on project needs and performance requirements. In some cases, Redis and MySQL can be used together to meet different types of transaction needs.

3. Redis transaction related commands

Redis transactions are a powerful feature that allow us to package a series of Redis commands together to ensure that they either all execute successfully or all fail. In Redis, there are some key commands used to process transactions, including MULTI, EXEC, DISCARD, WATCHand UNWATCH. The functions and usage of these commands will be introduced in detail below.

3.1 MULTI

MULTIThe command is used to start a transaction. After executing MULTIthe command, Redis will enter transaction mode, and subsequent commands will be added to the transaction queue to wait for execution. If executed successfully, MULTIthe command returns "OK".

Example:

127.0.0.1:6379> MULTI
OK

3.2 EXEC

EXECCommands are used to execute the command queue within a transaction. When executing EXECa command, Redis will execute these commands atomically one after another in the order of the commands in the transaction queue. If all commands in the transaction are executed successfully, EXECthe command returns an array containing the execution results of each command; if any command fails to execute, all commands in the transaction will be cancelled.

Example:

127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET k1 1
QUEUED
127.0.0.1:6379> SET k2 2
QUEUED
127.0.0.1:6379> SET k3 3
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) OK
3) OK

3.3 DISCARD

DISCARDThe command is used to abandon the current transaction. Executing DISCARDthe command will clear all commands in the transaction queue, and no previous operations will be actually executed.

Example:

127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET k1 1
QUEUED
127.0.0.1:6379> SET k2 2
QUEUED
127.0.0.1:6379> DISCARD
OK
127.0.0.1:6379> GET k1
(nil)
127.0.0.1:6379> GET k2
(nil)

3.4 WATCH

When executing a transaction, if a key in a transaction is modified by other clients, data inconsistency may occur. WATCHThe command is used to solve this problem. It can monitor a specified set of keys. If these keys are modified by other clients before the transaction is executed, the transaction will be cancelled.

Example:

# 客户端1 开始监控 k1
127.0.0.1:6379> WATCH k1
OK

# 客户端2 修改 k1
127.0.0.1:6379> SET k1 100
OK

# 客户端1 执行事务,但由于 k1 被修改,事务将被取消
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET k1 200
QUEUED
127.0.0.1:6379> EXEC
(nil)
# 获取 k1 的值
127.0.0.1:6379> GET k1
"100"

WATCH principle:

WATCHThe principle can be simply summarized into the following steps:

  1. The client executes WATCHthe command and specifies the keys to monitor.
  2. Redis creates a monitor (Watcher) on the server side to monitor these keys. The monitor records the current state of the monitored key, usually 版本号或时间戳.
  3. When the client enters transaction mode, it can execute multiple commands, but these commands will not be executed immediately, but will enter a queue to wait.
  4. Before executing a transaction, the client asks the server to check whether the state of the monitored key has changed in the monitor. This is done by comparing the state in the monitor to the state of the current key.
  5. If the monitor discovers that the state of the monitored key has changed before executing the transaction, it notifies the client to cancel the transaction. This is the core idea of ​​optimistic locking: if another client modifies the monitored key between execution WATCHand , then the transaction will fail.EXEC
  6. If the monitor detects no changes, the client can execute the commands in the transaction, which are executed sequentially.

In short, WATCHthe principle is to monitor the status of a set of keys by creating a monitor on the server side, and check whether the status of these keys has changed before executing a transaction. If another client modifies the monitored key, the transaction will be canceled to ensure data consistency. This enables Redis to implement transaction operations in a concurrent environment without causing problems such as race conditions.

3.5 UNWATCH

UNWATCHThe command is used to cancel key monitoring and is WATCHthe reverse operation of the command. If you no longer need to monitor certain keys, you can use UNWATCHto cancel monitoring.

127.0.0.1:6379> set key 1
OK
127.0.0.1:6379> WATCH key
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> set key 2
QUEUED
127.0.0.1:6379> set key 3
QUEUED
127.0.0.1:6379> DISCARD
OK
127.0.0.1:6379> UNWATCH
OK
127.0.0.1:6379> 

The above is a detailed introduction to Redis transaction related commands. By using these commands appropriately, you can build safe and reliable transaction operations to ensure data consistency and integrity. Of course, when using transactions, you need to decide whether to use monitoring commands based on specific business needs and situations WATCH.

4. Summary

In this article, we delve into the concept of Redis transactions and related commands, as well as the comparison of Redis transactions and MySQL transactions. Here is a summary of the main takeaways from this article:

  1. Core concepts of Redis transactions: Redis transactions allow multiple Redis commands to be packaged into a single, uninterruptible sequence of operations. This ensures that the commands either all succeed or all fail.

  2. Redis transaction related commands: Redis provides a set of key commands to manage transactions, including MULTI(start transaction), EXEC(commit transaction), DISCARD(cancel transaction), WATCH(monitor key changes), and UNWATCH(cancel monitor).

  3. Comparison of Redis transactions and MySQL transactions: Redis transactions and MySQL transactions differ in terms of transaction granularity, ACID properties, concurrency control, error handling, and application scenarios. Redis transactions are typically used for simple atomic operations, while MySQL transactions support a wider range of ACID properties and are suitable for applications that require strong transaction integrity.

  4. Limitations of Redis transactions: Redis transactions do not support the isolation levels and durability found in traditional databases, requiring the application to handle errors and rollback logic by itself.

When choosing between using Redis transactions or MySQL transactions, you should weigh the different features and limitations based on your project needs and performance requirements. Understanding how Redis transactions work and how to use them can help us make better use of Redis's transaction functions.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/132915120