Home >Database >Redis >Introduction to redis transactions and related commands

Introduction to redis transactions and related commands

尚
forward
2019-11-27 16:38:372599browse

Introduction to redis transactions and related commands

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 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: (Recommended: redis video tutorial)

1). All commands in the transaction will be executed in serial order. During the execution of the transaction, Redis will no longer provide any services for other client requests, thus ensuring that all commands in the transaction are Commands are executed atomically.

2). Compared with transactions in relational databases, if a command fails to execute in a Redis transaction, subsequent commands will 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. List of related commands:

Command prototype Time complexity Command description Return value

M

U

L

T

I


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

E

X

E

C


Execute all commands in the command queue within a transaction, and at the same time restore the status of the current connection to the normal state, that is, the non-transaction 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.
##D

I

S

C

A

R

D


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, the non-transaction state. If the WATCH command is used, this command will UNWATCH all Keys. Always returns OK.

W

A

T

C

H

k

e

y

[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.

U

N

W

A

T

C

H

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 the 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:
#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 return result of the command, we can see that 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

#A new command is executed. From the results, it can be seen that the command is also stored in the transaction's command queue.

redis 127.0.0.1:6379> incr t2
QUEUED

#Execute all commands in the transaction command queue. As can be seen from the results, the results of the commands in the queue are returned.

redis 127.0.0.1:6379> exec
1) (integer) 1
2) (integer) 1

2. There is a failed command in the transaction:
#Start a new transaction.

redis 127.0.0.1:6379> multi
OK

#Set the value of key a to 3 of string type.

redis 127.0.0.1:6379> set a 3
QUEUED

#Pop the element from the head of the value associated with key a. Since the value is a string type, and the lpop command can only be used for the List type, when executing the exec command, the The command will fail.

redis 127.0.0.1:6379> lpop a
QUEUED

#Set the value of key a to string 4 again.

redis 127.0.0.1:6379> set a 4
QUEUED

#Get the value of key a to confirm whether the value is set successfully by the second set command in the transaction.

redis 127.0.0.1:6379> get a
QUEUED

#It can be seen from the results that the second command lpop in the transaction failed to execute, but the subsequent set and get commands were executed successfully. This is the transaction and relational type of Redis. The most important difference between transactions in a 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. Rollback transaction:
#Set a value for key t2 before the transaction is executed.

redis 127.0.0.1:6379> set t2 tt
OK

#Open a transaction.

redis 127.0.0.1:6379> multi
OK

# Set a new value for this key within the transaction.

redis 127.0.0.1:6379> set t2 ttnew
QUEUED

#Abandon the transaction.

redis 127.0.0.1:6379> discard
OK

#View the value of key t2. From the results, we can see that the value of this key is still the value before the transaction started.

redis 127.0.0.1:6379> get t2
"tt"

4. WATCH command and CAS-based optimistic locking:

In Redis transactions, the WATCH command can be used to provide CAS (check -and-set) function. Assume that we monitor multiple Keys through the WATCH command before the transaction is executed. If the value of any Key changes after WATCH, the transaction executed by the EXEC command will be abandoned and a Null multi-bulk response will be returned to notify the caller of the transaction. Execution failed.

For example, we assume again that the incr command is not provided in Redis to complete the atomic increment of key values. If we want to implement this function, we can only write the corresponding code ourselves. The pseudo code is as follows:

      val = GET mykey
      val = val + 1
      SET mykey $val

The 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.

For example, clients A and B both 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 result of mykey to be 11, not 12 as we think. 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
      EXEC

The difference from the previous code is that the new code monitors the value of mykey through the WATCH command before getting it. key, and then surround the set command in a transaction, which can effectively ensure that before executing EXEC for each connection, if the value of mykey obtained by the current connection is modified by other connected clients, then the EXEC command of the current connection will be executed. fail. In this way, the caller can know whether val has been successfully reset after judging the return value.

For more redis knowledge, please pay attention to the redis tutorial column.

The above is the detailed content of Introduction to redis transactions and related commands. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete