Home > Article > Backend Development > Redis tutorial (8): Detailed explanation of transactions
1. Overview:
Like many other databases, Redis as a NoSQL database also provides a transaction mechanism. In Redis, the four commands MULTI/EXEC/DISCARD/WATCH are the cornerstone of our transaction implementation. I believe that this concept is not unfamiliar to developers with relational database development experience. Even so, we will briefly list the implementation characteristics of transactions in Redis:
1). In transactions All commands will be executed serially and sequentially. During the execution of the transaction, Redis will not provide any services for other client requests, thus ensuring that all commands in the transaction are executed atomically.
2). Compared with transactions in relational databases, if a command fails to execute in a Redis transaction, subsequent commands will still continue to be executed.
3). We can start a transaction through the MULTI command, which people with experience in relational database development can understand as the "BEGIN TRANSACTION" statement. The commands executed after this statement will be regarded as operations within the transaction. Finally, we can commit/rollback all operations within the transaction by executing the EXEC/DISCARD command. These two Redis commands can be regarded as equivalent to the COMMIT/ROLLBACK statement in a relational database.
4). Before the transaction is started, if there is a communication failure between the client and the server and the network is disconnected, all subsequent statements to be executed will not be executed by the server. However, if the network interruption event occurs after the client executes the EXEC command, then all commands in the transaction will be executed by the server.
5). When using the Append-Only mode, Redis will write all write operations in the transaction to the disk in this call by calling the system function write. However, if a system crash occurs during the writing process, such as a downtime caused by a power failure, then only part of the data may be written to the disk at this time, while other part of the data has been lost. The Redis server will perform a series of necessary consistency checks when restarting. Once a similar problem is found, it will exit immediately and give a corresponding error prompt. At this time, we must make full use of the redis-check-aof tool provided in the Redis toolkit. This tool can help us locate data inconsistency errors and roll back some of the data that has been written. After the repair, we can restart the Redis server again.
2. Related command list:
Command prototype | Time complexity | Command description | Return value |
MULTI | # is used to mark the beginning of a transaction. All commands executed thereafter will be stored in the command queue. These commands will not be executed atomically until EXEC is executed. . | Always returns OK | |
EXEC | Execute all commands in the command queue within a transaction, while Restore the status of the current connection to its normal state, that is, non-transactional state. If the WATCH command is executed during a transaction, the EXEC command can execute all commands in the transaction queue only if the Keys monitored by WATCH have not been modified. Otherwise, EXEC will abandon all commands in the current transaction. | Atomicly return the results of each command in the transaction. If WATCH is used in a transaction, EXEC will return a NULL-multi-bulk reply once the transaction is abandoned. | |
DISCARD | Roll back all commands in the transaction queue, and at the same time restore the status of the current connection to the normal state, that is Non-transaction status. If the WATCH command is used, this command will UNWATCH all Keys. | Always returns OK | |
WATCHkey [key ...] | O(1) | Before the MULTI command is executed, You can specify the Keys to be monitored. However, if the monitored Keys are modified before executing EXEC, EXEC will give up executing all commands in the transaction queue. | Always returns OK. |
UNWATCH | O(1) | Cancel the specified monitored Keys in the current transaction. If the EXEC or DISCARD command is executed, there is no need to manually Execute this command, because after this, all monitored Keys in the transaction will be automatically canceled. | Always returns OK. |
3. Command examples:
1. The transaction is executed normally:
#在Shell命令行下执行Redis的客户端工具。 /> redis-cli #在当前连接上启动一个新的事务。 redis 127.0.0.1:6379> multi OK #执行事务中的第一条命令,从该命令的返回结果可以看出,该命令并没有立即执行,而是存于事务的命令队列。 redis 127.0.0.1:6379> incr t1 QUEUED #又执行一个新的命令,从结果可以看出,该命令也被存于事务的命令队列。 redis 127.0.0.1:6379> incr t2 QUEUED #执行事务命令队列中的所有命令,从结果可以看出,队列中命令的结果得到返回。 redis 127.0.0.1:6379> exec 1) (integer) 1 2) (integer) 1
2. There is a failed command in the transaction:
#开启一个新的事务。 redis 127.0.0.1:6379> multi OK #设置键a的值为string类型的3。 redis 127.0.0.1:6379> set a 3 QUEUED #从键a所关联的值的头部弹出元素,由于该值是字符串类型,而lpop命令仅能用于List类型,因此在执行exec命令时,该命令将会失败。 redis 127.0.0.1:6379> lpop a QUEUED #再次设置键a的值为字符串4。 redis 127.0.0.1:6379> set a 4 QUEUED #获取键a的值,以便确认该值是否被事务中的第二个set命令设置成功。 redis 127.0.0.1:6379> get a QUEUED #从结果中可以看出,事务中的第二条命令lpop执行失败,而其后的set和get命令均执行成功,这一点是Redis的事务与关系型数据库中的事务之间最为重要的差别。 redis 127.0.0.1:6379> exec 1) OK 2) (error) ERR Operation against a key holding the wrong kind of value 3) OK 4) "4"
#为键t2设置一个事务执行前的值。 redis 127.0.0.1:6379> set t2 tt OK #开启一个事务。 redis 127.0.0.1:6379> multi OK #在事务内为该键设置一个新值。 redis 127.0.0.1:6379> set t2 ttnew QUEUED #放弃事务。 redis 127.0.0.1:6379> discard OK #查看键t2的值,从结果中可以看出该键的值仍为事务开始之前的值。 redis 127.0.0.1:6379> get t2 "tt"
4. WATCH command and CAS-based optimistic locking:
val = GET mykey val = val + 1 SET mykey $valThe above code can only guarantee that the execution result is correct in the case of a single connection, because if there are multiple clients executing this code at the same time, Then there will be an error scenario that often occurs in multi-threaded programs-race condition (race condition). For example, both clients A and B read the original value of mykey at the same time. Assume that the value is 10. After that, both clients add one to the value and set it back to the Redis server. This will cause the value of mykey to be lost. The result is 11, not 12 as we thought. In order to solve similar problems, we need the help of the WATCH command, see the following code:
WATCH mykey val = GET mykey val = val + 1 MULTI SET mykey $val EXECThe difference from the previous code is that the new code monitors the key through the WATCH command before obtaining the value of mykey, and then The set command is also surrounded by a transaction, which can effectively ensure that before each connection executes EXEC, if the value of mykey obtained by the current connection is modified by other connected clients, the EXEC command of the current connection will fail to execute. In this way, the caller can know whether val has been successfully reset after judging the return value. The above is the content of Redis Tutorial (8): Detailed Transactions. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!