Redis learning Manual (Transaction)

Source: Internet
Author: User
Tags redis server

I. Overview:

Like many other databases, redis also provides a transaction mechanism as a nosql database. In redis, the four commands multi/exec/discard/watch are the cornerstone of our transaction implementation. I believe this concept is no stranger to developers with relational database development experience. Even so, we will briefly list the transaction implementation features in redis:
1 ). all commands in the transaction will be executed in a serialized order. During the transaction execution, redis will not provide any service for requests from other clients, this ensures that all commands in a transaction are executed by atoms.
2). Compared with a transaction in a relational database, if a command fails to be executed in a redis transaction, the subsequent command will still be executed.
3). We can use the multi command to start a transaction. People with experience in relational database development can understand it as a "begin transaction" statement. The commands executed after this statement are considered as operations in the transaction. Finally, we can commit/roll back all operations in the transaction by executing the exec/Discard command. The two redis commands can be considered to be equivalent to the commit/rollback statements in relational databases.
4). Before the transaction is started, if the communication between the client and the server fails and the network is disconnected, all the statements to be executed will not be executed by the server. However, if the network interruption occurs after the client executes the exec command, all the commands in the transaction will be executed by the server.
5) when the append-only mode is used, redis will write all write operations in the transaction to the disk by calling the system function write. However, if a system crash occurs during the write process, such as a power failure, only some data may be written to the disk, but other data may be lost. The redis server performs a series of necessary consistency checks when it is restarted. Once a similar problem is found, it immediately exits and provides an error message. In this case, 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 data that has been written. After the repair, we can restart the redis server again.

Ii. Related command list:

Command prototype Time Complexity Command description Return Value
Multi   It is used to mark the start of a transaction, and subsequent commands will be stored in the command queue. These commands will not be executed by atoms until exec is executed. Always Return OK
Exec   Execute all the commands in the command queue in a transaction and restore the current connection status to normal, that is, non-transaction status. If the watch command is executed in a transaction, only when the keys monitored by watch are not modified can the exec command execute all the commands in the transaction queue, otherwise, exec will discard all commands in the current transaction. Atomically return the results of each command in the transaction. If watch is used in the transaction, once the transaction is abandoned, exec returns a null-Multi-bulk reply.
Discard   Roll back all commands in the transaction queue, and then restore the current connection status to normal, that is, non-transaction status. If the watch command is used, it will unwatch all keys. Always Return OK.
WatchKey [Key...] O (1) You can specify the keys to be monitored before executing the multi command. However, if the monitored keys are modified before exec is executed, exec will discard all commands in the transaction queue. Always Return OK.
Unwatch O (1) Cancels the specified monitored keys in the current transaction. If the exec or discard command is executed, you do not need to manually execute the command because after that, all monitored keys in the transaction are automatically canceled. Always Return OK.

Iii. Command example:

1. The transaction is executed normally:
# Execute the redis client tool under the shell command line.
/> Redis-cli
# Start a new transaction on the current connection.
Redis 127.0.0.1: 6379> Multi
OK
# Execute the first command in the transaction. From the result returned by the command, we can see that the command is not executed immediately, but saved in the command queue of the transaction.
Redis 127.0.0.1: 6379> Incr T1
Queued
# Execute a new command. The result shows that the command is also stored in the command queue of the transaction.
Redis 127.0.0.1: 6379> Incr T2
Queued
# Execute all the commands in the transaction command queue. The result shows that the command results in the queue are returned.
Redis 127.0.0.1: 6379> Exec
1) (integer) 1
2) (integer) 1

2. A failed command exists in the transaction:
# Start a new transaction.
Redis 127.0.0.1: 6379> Multi
OK
# Set the value of key a to 3 of the string type.
Redis 127.0.0.1: 6379> Set a 3
Queued
# The pop-up element in the header of the value associated with key A. Because the value is of the string type, the lpop command can only be used for the list type. Therefore, when executing the exec command, this command will fail.
Redis 127.0.0.1: 6379> Lpop
Queued
# Set the value of key a to string 4 again.
Redis 127.0.0.1: 6379> Set a 4
Queued
# Obtain the value of key a to check whether the value is successfully set by the second set command in the transaction.
Redis 127.0.0.1: 6379> Get
Queued
# From the results, we can see that the second lpop command in the transaction fails to be executed, and the subsequent set and get commands are successfully executed, this is the most important difference between redis transactions and those in relational databases.
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. roll back the transaction:
# Set the value before the execution of a transaction for key T2.
Redis 127.0.0.1: 6379> Set T2 TT
OK
# Start a transaction.
Redis 127.0.0.1: 6379> Multi
OK
# Set a new value for the key in the transaction.
Redis 127.0.0.1: 6379> Set T2 ttnew
Queued
# Discard the transaction.
Redis 127.0.0.1: 6379> Discard
OK
# Check the value of the key T2. The result shows that the key value is still the value before the start of the transaction.
Redis 127.0.0.1: 6379> Get T2
"TT"

4. Watch commands and CAS-based Optimistic locks:

In redis transactions, the watch command can be used to provide the CAS (check-and-set) function. Assume that we use the watch command to monitor multiple keys before the transaction is executed. If any key value changes after the watch command, the transaction executed by the exec command will be abandoned, at the same time, null multi-bulk response is returned to notify the caller that the transaction failed. For example, we assume that redis does not provide the incr command to increase the atomicity of the key value. To implement this function, we can write the corresponding Code . The pseudo code is as follows:
Val = get mykey
Val = Val + 1
Set mykey $ Val
The above code can ensure that the execution result is correct only when a single connection occurs, because if multiple clients execute this code at the same time, multiple threads will occur. Program Race Condition is a common error scenario ). For example, both client a and client B read the original value of mykey at the same time. If the value is 10, then both clients add this value to the redis server and set it back to the redis server, in this way, the mykey result is 11 instead of 12. To solve similar problems, we need to use the watch command for help. See the following code:
Watch mykey
Val = get mykey
Val = Val + 1
Multi
Set mykey $ Val
Exec
Unlike the previous Code, the new Code monitors the key through the watch command before obtaining the value of mykey, and then wraps the SET command in the transaction, this effectively ensures that the value of the mykey obtained by the current connection is modified by the client of another connection before executing exec. The exec command of the current connection fails to be executed. In this way, the caller can determine whether the Val has been reset successfully after determining the return value.

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.