深度挖掘Redis之多命令 Atomic 操作multi redis.multi

2023-12-21 18:02:55网络知识悟空

The command “MULTI” of Redis is the antithetical command of the ordinary commands. All data operations that occur after MULTI commands are considered transactions, which can be carried out independently, rather than directly driving the db. The purpose of the MULTI command is to atomize the previously separate operations into one transaction.

MULTI is the cornerstone of the Redis transaction, and it is not allowed to directly perform the command outside MULTI within a transaction. It can only be access commands. For example, if you want to batch delete data in Redis, you can use the MULTI command to wrap up the DELETE command for atomic operation.

Redis multi, exec two commands belong to the command set. The use of MULTI and EXEC, using redis atomic transactions to ensure the data accuracy of the database. Redis transactions are intended to ensure that a group of commands execute all or nothing.

The following is the code example of Redis multi atomic operation, in which multi is the beginning of a transaction, and exec completes the batch execution, while discard removes all commands in the transaction after multi mode:

MULTI
SET redis transation test
INCR table_row_value
EXEC

When Redis’s multi command executes, all the operations of the command are placed in an internal buffer and are not executed immediately. After the EXEC command executions, the operations contained in the command will be executed in an atomic manner.

In conclusion, Redis atomic operation is inherently very useful, but do not abuse it. Redis atomic operation has a certain overhead, and two or more lines of operations that can be implemented in one line do not need atomic operation. Therefore, the MULTI or EXEC command should be used reasonably, try to reduce the number of atomic operations, and pay attention to the performance indicators in the project log.

发表评论: