Table of Contents
Introduction to Redis transactions
Redis basic transaction instructions
Example analysis
Redis 事务与 ACID
Home Database Redis An article will help you thoroughly understand Redis affairs

An article will help you thoroughly understand Redis affairs

Nov 01, 2022 pm 01:48 PM
redis

This article brings you relevant knowledge about Redis, which mainly introduces the relevant content about transactions. It is essentially a collection of commands. Transactions support the execution of multiple commands at one time. , during the transaction execution process, the commands in the queue will be executed sequentially; let's take a look at it, I hope it will be helpful to everyone.

Recommended learning: Redis video tutorial

Introduction to Redis transactions

Redis is just Provides simple transaction functions. Its essence is a set of commands. A transaction supports the execution of multiple commands at one time. During the transaction execution process, the commands in the queue will be executed sequentially. Command requests submitted by other clients will not be inserted into the sequence of commands executed by this transaction. The execution process of commands is executed sequentially, but atomicity is not guaranteed. There is no isolation level like MySQL, and you can roll back data and other advanced operations after a problem occurs. This will be analyzed in detail later.

Redis basic transaction instructions

Redis provides the following basic instructions related to transactions.

MULTI When the transaction is enabled, Redis will add subsequent commands to the queue without actually executing them until EXEC is used to execute these commands in atomic order. EXECExecute all commands in the transaction blockDISCARDCancel the transaction and give up executing all commands in the transaction blockWATCHMonitor one or more keys, if the transaction is executing If these keys are modified by other commands before, the transaction will be terminated and no commands in the transaction will be executed UNWATCHCancelWATCHThe command monitors all keys

General In this case, a simple Redis transaction is mainly divided into the following parts:

Execute the command MULTI to start a transaction. After the transaction is started, multiple commands to execute the command will be put into a queue in sequence. If the placement is successful, the QUEUED message will be returned. Execute the command EXEC to submit the transaction. Redis will execute the commands in the queue in sequence and return the results of all commands in sequence. (If you want to give up committing the transaction, execute DISCARD).

The following figure briefly introduces the process of Redis transaction execution:

Example analysis

Let’s go through some practical examples below. Let’s experience the transactions in Redis. We also mentioned earlier that Redis transactions are not real transactions and cannot fully meet the ACID characteristics of standard transactions. Through the following example, let's take a look at what are the problems with Redis's "bankrupt version" transaction.

[A] Normal execution of submission

127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET a 1
QUEUED
127.0.0.1:6379> SET b 2
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) OK
127.0.0.1:6379> GET a
"1"
127.0.0.1:6379> GET b
"2"
Copy after login

After opening the transaction, the submitted commands will be added to the queue (QUEUED). After executing EXEC, the commands will be executed step by step and the results will be returned. Does this look similar to the transaction operations we usually use in MySQL, such as start transaction and commit?

[B]Cancel the transaction normally

127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET a 1
QUEUED
127.0.0.1:6379> SET b 2
QUEUED
127.0.0.1:6379> DISCARD
OK
127.0.0.1:6379> 
127.0.0.1:6379> GET a
(nil)
127.0.0.1:6379> GET b
(nil)
Copy after login

After opening the transaction, if you do not want to continue the transaction, use DISCARD to cancel it. The previously submitted command will not actually be executed, and the related key value will not change. This also looks similar to MySQL transactions, similar to start transaction and rollback.

[C]WATCH monitoring key

-- 线程 1 中执行
127.0.0.1:6379> del a
(integer) 1
127.0.0.1:6379> get a
(nil)
127.0.0.1:6379> SET a 0
OK
127.0.0.1:6379> WATCH a
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET a 1
QUEUED
----------------------------------------- 线程 2 中执行
----------------------------------------- 127.0.0.1:6379> SET a 2
----------------------------------------- OK
127.0.0.1:6379> EXEC
(nil)
127.0.0.1:6379> GET a
"2"
Copy after login

WATCH the value of a before opening the transaction, and then open the transaction. The value of a is set in another thread (SET a 2), and then EXEC is executed to execute the transaction. The result is nil,
indicating that the transaction has not been executed. Because the value of a changed after WATCH, the transaction was canceled.

It should be noted that this has nothing to do with the time when the transaction is started, and has nothing to do with the order in which MULTI and another thread set the value of a. As long as it changes after WATCH. Regardless of whether the transaction has been started, it will be canceled when executing the transaction (EXEC).
Under normal circumstances, when executing EXEC and DISCARD commands, UNWATCH will be executed by default.

[D] Syntax error

127.0.0.1:6379> SET a 1
OK
127.0.0.1:6379> SET b 2
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET a 11
QUEUED
127.0.0.1:6379> SETS b 22
(error) ERR unknown command 'SETS'
127.0.0.1:6379> EXEC
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> GET a
"1"
127.0.0.1:6379> GET b
"2"
Copy after login

When Redis starts a transaction, if there is a syntax error in the added command, the transaction submission will fail. In this case, none of the commands in the transaction queue will be executed. As in the above example, the values ​​of a and b are both original values.
Such errors that occur before EXEC, such as command name errors, command parameter errors, etc., will be detected before EXEC is executed. Therefore, when these errors occur, the transaction will be canceled and all commands in the transaction will be canceled. Will not be executed. (Does this situation look a bit like a rollback?)

[E]Runtime error

127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET a 1
QUEUED
127.0.0.1:6379> SET b hello
QUEUED
127.0.0.1:6379> INCR b
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) OK
3) (error) ERR value is not an integer or out of range
127.0.0.1:6379> GET a
"1"
127.0.0.1:6379> GET b
"hello"
Copy after login

当 Redis 开启一个事务后,添加的命令没有出现前面说的语法错误,但是在运行时检测到了类型错误,导致事务最提交失败(说未完全成功可能更准确点)。此时事务并不会回滚,而是跳过错误命令继续执行。
如上面的例子,未报错的命令值已经修改,a 被设置成了 1,b 被设置为了 hello,但是报错的值未被修改,即 INCR b 类型错误,并未执行,b 的值也没有被再更新。

Redis 事务与 ACID

通过上面的例子,我们已经知道 Redis 的事务和我们通常接触的 MySQL 等关系数据库的事务还有有一定差异的。它不保证原子性。同时 Redis 事务也没有事务隔离级别的概念。下面我们来具体看下 Redis 在 ACID 四个特性中,那些是满足的,那些是不满足的。
事务执行可以分为命令入队(EXEC 执行前)和命令实际执行(EXEC 执行之后)两个阶段。下面我们在分析的时候,很多时候都会分这两种情况来分析。

原子性(A)

上面的实例分析中,[A],[B],[C]三种正常的情况,我们可以很明显的看出,是保证了原子性的。
但是一些异常情况下,是不满足原子性的。

如 [D] 所示的情况,客户端发送的命令有语法错误,在命令入队列时 Redis 就判断出来了。等到执行 EXEC 命令时,Redis 就会拒绝执行所有提交的命令,返回事务失败的结果。此种情况下,事务中的所有命令都不会被执行了,是保证了原子性的。 如 [E] 所示的情况,事务操作入队时,命令和操作类型不匹配,此时 Redis 没有检查出错误(这类错误是运行时错误)。等到执行 EXEC 命令后,Redis 实际执行这些命令操作时,就会报错。需要注意的是,虽然 Redis 会对错误的命令报错不执行,但是其余正确的命令会依次执行完。此种情况下,是无法保证原子性的。 在执行事务的 EXEC 命令时,Redis 实例发生了故障,导致事务执行失败。此时,如果开启了 AOF 日志,那么只会有部分事务操作被记录到 AOF 日志中。使用redis-check-aof工具检测 AOF 日志文件,可以把未完成的事务操作从 AOF 文件中去除。这样一来,使用 AOF 文件恢复实例后,事务操作不会被再执行,从而保证了原子性。若使用的 RDB 模式,最新的 RDB 快照是在 EXEC 执行之前生成的,使用快照恢复之后,事务中的命令也都没有执行,从而保证了原子性。若 Redis 没有开启持久化,则重启后内存中的数据全部丢失,也就谈不上原子性了。 一致性(C)

一致性指的是事务执行前后,数据符合数据库的定义和要求。这点在 Redis 事务中是满足的,不论是发生语法错误还是运行时错误,错误的命令均不会被执行。

EXEC 执行之前,入队报错(实例分析中的语法错误)

事务会放弃执行,故可以保证一致性。

EXEC 执行之后,实际执行时报错(实例分析中的运行时错误)

错误的命令不会被执行,正确的命令被执行,一致性可以保证。

EXEC 执行时,实例宕机

若 Redis 没有开启持久化,实例宕机重启后,数据都没有了,数据是一致的。
若配置了 RDB 方式,RDB 快照不会在事务执行时执行。所以,若事务执行到一半,实例发生了故障,此时上一次 RDB 快照中不会包含事务所做的修改,而下一次 RDB 快照还没有执行,实例重启后,事务修改的数据会丢失,数据是一致的。若事务已经完成,但新一次的 RDB 快照还没有生成,那事务修改的数据也会丢失,数据也是一致的。
若配置了 AOF 方式。当事务操作还没被记录到 AOF 日志时,实例就发生故障了,使用 AOF 日志恢复后数据是一致的。若事务中的只有部分操作被记录到 AOF 日志,可以使用 redis-check-aof清除事务中已经完成的操作,数据库恢复后数据也是一致的。

隔离性(I) 并发操作在 EXEC 执行前,隔离性需要通过 WATCH 机制来保证 并发操作在 EXEC 命令之后,隔离性可以保证

情况 a 可以参考前面的实例分析 WATCH 命令的使用。
情况 b,由于 Redis 是单线程执行命令,EXEC 命令执行后,Redis 会保证先把事务队列中的所有命令执行完之后再执行之后的命令。

持久性(D)

If Redis does not enable persistence, then all data will be stored in memory. Once restarted, the data will be lost, so the durability of the transaction at this time cannot be guaranteed.
If Redis has persistence turned on, data may still be lost when the instance crashes and is restarted, so persistence cannot be fully guaranteed.
Therefore, we can say that Redis transactions cannot necessarily guarantee durability, and can only guarantee durability under special circumstances.

Regarding why Redis still loses data after turning on persistence, the author will compile a separate article related to Redis persistence and master-slave to introduce it. Here is a brief introduction.
If the RDB mode is configured, after a transaction is executed but before the next RDB snapshot is executed, the Redis instance crashes and the data will be lost.
If the AOF mode is configured, and the three parameters of the AOF mode The configuration options no, everysec, and always may also cause data loss.

To summarize, Redis transactions support ACID:

It has a certain degree of atomicity, but does not support rollback. It meets consistency and isolation and cannot guarantee durability. Why does Redis transaction not support rollback? Roll

Look at the description on the official website:

What about rollbacks?
Redis does not support rollbacks of transactions since supporting rollbacks would have a significant impact on the simplicity and performance of Redis.

Most situations that require transaction rollback are caused by program errors. This situation is generally in the development environment and should not occur in the production environment.
For logical errors, for example, it should add 1, but the result is written as adding 2. This situation cannot be solved by rolling back.
Redis pursues simplicity and efficiency, but the implementation of traditional transactions is relatively complex, which is contrary to the design idea of ​​Redis. When we enjoy the speed of Redis, we can't ask for more from it.

Recommended learning: Redis video tutorial

The above is the detailed content of An article will help you thoroughly understand Redis affairs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

See all articles