Home Database Redis Introduction to redis transactions and related commands

Introduction to redis transactions and related commands

Nov 27, 2019 pm 04:38 PM
redis

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
Copy after login

#Start a new transaction on the current connection.

redis 127.0.0.1:6379> multi
OK
Copy after login
Copy after login
Copy after login

#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
Copy after login

#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
Copy after login

#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
Copy after login

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

redis 127.0.0.1:6379> multi
OK
Copy after login
Copy after login
Copy after login

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

redis 127.0.0.1:6379> set a 3
QUEUED
Copy after login

#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
Copy after login

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

redis 127.0.0.1:6379> set a 4
QUEUED
Copy after login

#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
Copy after login

#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
Copy after login

#Open a transaction.

redis 127.0.0.1:6379> multi
OK
Copy after login
Copy after login
Copy after login

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

redis 127.0.0.1:6379> set t2 ttnew
QUEUED
Copy after login

#Abandon the transaction.

redis 127.0.0.1:6379> discard
OK
Copy after login

#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"
Copy after login

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
Copy after login

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
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

See all articles