search
HomeDatabaseRedisIntroduction to redis transactions and related commands

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:博客园. If there is any infringement, please contact admin@php.cn delete
Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis: Understanding NoSQL ConceptsRedis: Understanding NoSQL ConceptsApr 21, 2025 am 12:04 AM

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.