Redis Tutorial (Eight): A detailed explanation of the transaction

Source: Internet
Author: User
Tags redis server redis tutorial

Reproduced in: http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/135.html?1455806987

First, overview:

Like many other databases, Redis also provides a transactional mechanism as a NoSQL database. In Redis, the multi/exec/discard/watch of these four commands is the cornerstone of our implementation of a transaction. I believe that this concept is not unfamiliar to developers with relational database development experience, even though we will briefly list the implementation characteristics of the transactions in Redis:

1). All commands in a transaction will be executed serially, and Redis will no longer provide any service for requests from other clients during transaction execution, thus guaranteeing that all commands in the thing are executed atomically.

2). Compared to transactions in a relational database, if a single command fails to execute in a Redis transaction, subsequent commands are still executed.
3). We can start a transaction with the Multi command, and someone with a relational database development experience can interpret it as a "BEGIN TRANSACTION" statement. The commands executed after the statement are treated as operations within the transaction, and finally we can commit/rollback all operations within the transaction by executing the Exec/discard command. These two Redis commands can be considered equivalent to commit/rollback statements in a relational database.

4). Before the transaction is opened, if there is a communication failure between the client and the server and causes the network to disconnect, then all statements to be executed will not be executed by the server. However, if a network outage event occurs after the client executes the EXEC command, all commands in the transaction are executed by the server.

5). When using append-only mode, Redis writes all writes within the transaction to disk in this call by calling the system function write. However, if a system crash occurs during the write process, such as an outage due to a power failure, then perhaps only some of the data is written to disk, while the other part of the data is lost. The Redis server performs a series of necessary consistency checks on reboot and, once a similar problem is found, exits immediately and gives the appropriate error prompt. At this point, we need to take full advantage of the REDIS-CHECK-AOF tools available in the Redis Toolkit, which can help us locate errors in data inconsistencies and roll back some of the data that has already been written. After the repair, we can restart the Redis server again.

Ii. List of related commands:

Command prototypes Complexity of Time Command description return value
MULTI Used to mark the start of a transaction, and subsequent commands will be stored in the command queue until the exec is executed, and the commands are executed by the atom. Always return OK
Exec Executes all commands in a command queue within a transaction, while restoring the state of the current connection to a normal state, that is, a non-transactional state. If the watch command is executed in a transaction, the EXEC command can execute all commands in the transaction queue only if the keys monitored by watch are not modified, or exec discards all commands in the current transaction. atomically returns the result of the command in the returned transaction. If watch is used in a transaction, EXEC returns a null-multi-bulk reply once the transaction is discarded.
DISCARD Rolls back all the commands in the transaction queue and then restores the state of the current connection to a normal state, that is, a non-transactional state. If the watch command is used, the command will unwatch all keys. Always return OK.
WATCHkey [key ...] O (1) Before the Multi command executes, the keys to be monitored can be specified, but exec discards all commands in the transaction queue if the monitored keys change before exec executes. Always return OK.
Unwatch O (1) Cancels the keys for the specified monitoring in the current transaction, and if the exec or discard command is executed, no more manual execution of the command is required because after that, all the monitored keys in the transaction are automatically canceled. Always return OK.

#p # pagination Title #e#

Examples of commands:

1. The transaction is performed normally:

The code is as follows:


#在Shell命令行下执行Redis的客户端工具.
/> REDIS-CLI
#在当前连接上启动一个新的事务.
Redis 127.0.0.1:6379> Multi
Ok
#执行事务中的第一条命令, as can be seen from the return result of this command, the command is not executed immediately, but is stored in the command queue of the transaction.
Redis 127.0.0.1:6379> incr T1
QUEUED
#又执行一个新的命令, it can be seen from the result that the command is also stored in the command queue of the transaction.
Redis 127.0.0.1:6379> incr T2
QUEUED
#执行事务命令队列中的所有命令, as you can see from the results, the results of the command in the queue are returned.
Redis 127.0.0.1:6379> exec
1) (integer) 1
2) (integer) 1


2. There are failed commands in the transaction:

The code is as follows:


#开启一个新的事务.
Redis 127.0.0.1:6379> Multi
Ok
#设置键a的值为string类型的3.
Redis 127.0.0.1:6379> Set a 3
QUEUED
#从键a所关联的值的头部弹出元素, because the value is a string type, and the Lpop command can only be used with the list type, the command will fail when the EXEC command is executed.
Redis 127.0.0.1:6379> Lpop A
QUEUED
#再次设置键a的值为字符串4.
Redis 127.0.0.1:6379> Set a 4
QUEUED
#获取键a的值 to confirm that the value was successfully set by the second set command in the transaction.
Redis 127.0.0.1:6379> Get a
QUEUED
#从结果中可以看出, the second command in a transaction fails Lpop execution, and the subsequent set and get commands are successful, which is the most important difference between a Redis transaction and a transaction in a relational database.
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"


3. Rolling back a transaction:

The code is as follows:

#p # pagination Title #e#
#为键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的值, you can see from the result that the value of the key is still the value before the start of the transaction.
Redis 127.0.0.1:6379> Get T2
"TT"


Iv. Watch command and CAS-based optimistic locking:

In a redis transaction, the Watch command can be used to provide CAS (check-and-set) functionality. Suppose we monitor multiple keys before a transaction executes through the Watch command, and if any key value changes after watch, the EXEC command executes the transaction is discarded, and a null Multi-bulk answer is returned to inform the caller that the transaction execution failed. For example, once again, we assume that Redis does not provide the INCR command to achieve the atomic increment of the key values, and we can only write the corresponding code ourselves if we want to implement this function. The pseudo code is as follows:

The code is as follows:


val = GET MyKey
val = val + 1
SET MyKey $val


The above code is guaranteed to be correct only in the case of a single connection, because if more than one client is executing the code at the same time, there is a common error scenario in a multithreaded program-race contention (race condition). For example, both client A and B read the original value of the MyKey at the same time, assuming that the value is 10, and then two clients then add the value one after another set back to the Redis server, which results in a mykey result of 11 instead of 12 as we think. To solve a similar problem, we need the help of the Watch command, as shown in the following code:

The code is as follows:


WATCH MyKey
val = GET MyKey
val = val + 1
MULTI
SET MyKey $val
Exec


Unlike the previous code, the new code monitors the key with the watch command before it gets the value of MyKey, and then encloses the set command in the transaction, which effectively guarantees that each connection is executed before exec, if the value of the MyKey that is obtained by the current connection is modified by the other connected clients. The EXEC command that is currently connected will fail to execute. This allows the caller to know if the Val has been reset successfully after judging the return value.

Redis Tutorial (Eight): A detailed explanation of the transaction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.