[Fun with Redis Interview Part 2] The interviewer asks about Redis affairs and threw this article to him

1. Redis transaction life cycle

  • Open transaction: use MULTI to open a transaction

  • Command into the queue: each operation command will be added to a queue, but the command will not be executed at this time

  • Commit the transaction: use the EXEC command to commit the transaction and start to execute the commands in the queue sequentially

2. Are Redis transactions atomic?

First look at the definition of atomicity in the relational database ACID:

Atomicity: All operations in a transaction are either completed or not completed at all, and will not end in a certain link in the middle. If an error occurs during the execution of the transaction, it will be restored (Rollback) to the state before the transaction started, as if the transaction had never been executed.

The official document defines the affairs:

  • The transaction is a separate isolated operation : all commands in the transaction are serialized and executed sequentially. During the execution of the transaction, it will not be interrupted by command requests sent by other clients.

  • A transaction is an atomic operation : either all commands in the transaction are executed, or none of them are executed. The EXEC command is responsible for triggering and executing all commands in the transaction: if the client fails to execute EXEC because of a disconnection after opening a transaction using MULTI, all commands in the transaction will not be executed. On the other hand, if the client successfully executes EXEC after opening the transaction, all commands in the transaction will be executed.

Officials believe that Redis transactions are an atomic operation, which is considered from the perspective of execution. But from the definition of ACID atomicity, Redis transactions are non-atomic in a strict sense , because in the process of command execution, once a command execution error occurs, Redis will not stop execution and roll back the data.

3. Why doesn't Redis support roll back?

Although the Redis command may fail to execute during the transaction, Redis will still execute the remaining commands in the transaction without performing the rollback operation. If you are familiar with mysql relational database transactions, you will be very confused about this. The official reason for Redis is as follows:

Only when the called Redis command has a syntax error, this command will fail to execute (Redis can find such problems during the time the command is placed in the transaction queue), or execute a key that does not conform to its data type Operation: In fact, this means that only program errors can cause Redis command execution failures. Such errors are likely to be found during program development, but are rarely found in the production environment. The ability to support transaction rollback will lead to complex design, which is contrary to the original intention of Redis. The design goal of Redis is to simplify functions and ensure faster operation speed.

There is a general objection to this official reason: what if the program has a bug? But in fact, regression cannot solve program bugs. For example, a careless programmer planned to update key A, but in fact finally updated key B. The rollback mechanism cannot solve this kind of human error. Because this kind of human error is unlikely to enter the production system, the official design of Redis chooses a simpler and faster method, and there is no mechanism to implement a rollback.

4. Redis transaction failure scenario

There are three types of failure scenarios:

(1) Before the transaction is submitted, the command cache (queue) executed by the client fails, such as the syntax error of the command (the number of command parameters is wrong, the command is not supported, etc.). If this type of error occurs, Redis will return a response containing the error message to the client, and Redis will clear the commands in the queue and cancel the transaction.

127.0.0.1:6379> set name xiaoming # 事务之前执行
OK
127.0.0.1:6379> multi # 开启事务
OK
127.0.0.1:6379> set name zhangsan # 事务中执行,命令入队列
QUEUED
127.0.0.1:6379> setset name zhangsan2 # 错误的命令,模拟失败场景
(error) ERR unknown command `setset`, with args beginning with: `name`, `zhangsan2`,
127.0.0.1:6379> exec # 提交事务,发现由于上条命令的错误导致事务已经自动取消了
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> get name # 查询name,发现未被修改
"xiaoming"

(2) After the transaction is submitted, the commands will be executed sequentially. The commands previously cached in the queue may fail to execute.

127.0.0.1:6379> multi # 开启事务
OK
127.0.0.1:6379> set name xiaoming # 设置名字
QUEUED
127.0.0.1:6379> set age 18 # 设置年龄
QUEUED
127.0.0.1:6379> lpush age 20 # 此处仅检查是否有语法错误,不会真正执行
QUEUED
127.0.0.1:6379> exec # 提交事务后开始顺序执行命令,第三条命令执行失败
1) OK
2) OK
3) (error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379> get name # 第三条命令失败没有将前两条命令回滚
"xiaoming"

(3) Due to optimistic lock failure, all previously cached command sequences will be discarded when the transaction is committed. Simulate this failure scenario by opening two redis clients and combining the watch command.

# 客户端1
127.0.0.1:6379> set name xiaoming # 客户端1设置name
OK
127.0.0.1:6379> watch name # 客户端1通过watch命令给name加乐观锁
OK
# 客户端2
127.0.0.1:6379> get name # 客户端2查询name
"xiaoming"
127.0.0.1:6379> set name zhangsan # 客户端2修改name值
OK
# 客户端1
127.0.0.1:6379> multi # 客户端1开启事务
OK
127.0.0.1:6379> set name lisi # 客户端1修改name
QUEUED
127.0.0.1:6379> exec # 客户端1提交事务,返回空
(nil)
127.0.0.1:6379> get name # 客户端1查询name,发现name没有被修改为lisi
"zhangsan"

During the transaction, the monitored key is changed by other clients, the optimistic lock of the current client fails, and all command cache queues will be discarded when the transaction is submitted.

5. Redis transaction related commands

(1)WATCH

Can provide check-and-set (CAS) behavior for Redis transactions. The WATCH keys will be monitored and will find out whether these keys have been changed. If at least one monitored key is modified before EXEC is executed, the entire transaction will be cancelled, and EXEC returns nil-reply to indicate that the transaction has failed.

(2)MULTI

Used to start a transaction, it always returns OK. After MULTI is executed, the client can continue to send any number of commands to the server. These commands will not be executed immediately, but will be placed in a queue. When the EXEC command is called, all the commands in the queue will be executed.

(3) UNWATCH

Cancel the monitoring of all keys by the WATCH command, which is generally used before the DISCARD and EXEC commands. If after executing the WATCH command, the EXEC command or DISCARD command is executed first, then there is no need to execute UNWATCH again. Because the EXEC command executes the transaction, the effect of the WATCH command has been produced; and the DISCARD command cancels the transaction while also canceling all key monitoring, so after these two commands are executed, there is no need to execute UNWATCH.

(4)DISCARD

When the DISCARD command is executed, the transaction will be abandoned, the transaction queue will be emptied, and the client will exit from the transaction state.

(5)EXEC

Responsible for triggering and executing all commands in the transaction:

If the client executes EXEC after successfully opening the transaction, all commands in the transaction will be executed.

If the client fails to execute EXEC because of the disconnection after opening the transaction using MULTI, all commands in the transaction will not be executed. Special attention is needed: even if a certain/certain command in the transaction fails to execute, other commands in the transaction queue will continue to be executed, Redis will not stop executing the commands in the transaction, and it will not be like the relationship we usually use The same type of database rollback.

- END -

 

The technology of laugh-loving architects is not too bad. Wechat search for "Laughing Architect" and follow the official account, and more technical dry goods will be posted as soon as possible!

Finally, I will give you a bonus. The laughable architect has collected a lot of genuine e-books on related technologies. After paying attention to the official account, reply to the number 888 to get it for free.

 

Guess you like

Origin blog.csdn.net/guoguo527/article/details/108805546