Redis tutorial (8): Detailed explanation of transactions
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 that 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:
1). In transactions All commands will be executed serially and sequentially. During the execution of the transaction, Redis will not provide any services for other client requests, thus ensuring that all commands in the transaction are executed atomically.
2). Compared with transactions in relational databases, if a command fails to execute in a Redis transaction, subsequent commands will still 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. Related command list:
Command prototype | Time complexity | Command description | Return value |
MULTI | # 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 | |
EXEC | Execute all commands in the command queue within a transaction, while Restore the status of the current connection to its normal state, that is, non-transactional 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. | |
DISCARD | 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 Non-transaction status. If the WATCH command is used, this command will UNWATCH all Keys. | Always returns OK | |
WATCHkey [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. |
UNWATCH | 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 this 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:
#在Shell命令行下执行Redis的客户端工具。 /> redis-cli #在当前连接上启动一个新的事务。 redis 127.0.0.1:6379> multi OK #执行事务中的第一条命令,从该命令的返回结果可以看出,该命令并没有立即执行,而是存于事务的命令队列。 redis 127.0.0.1:6379> incr t1 QUEUED #又执行一个新的命令,从结果可以看出,该命令也被存于事务的命令队列。 redis 127.0.0.1:6379> incr t2 QUEUED #执行事务命令队列中的所有命令,从结果可以看出,队列中命令的结果得到返回。 redis 127.0.0.1:6379> exec 1) (integer) 1 2) (integer) 1
2. There is a failed command in the transaction:
#开启一个新的事务。 redis 127.0.0.1:6379> multi OK #设置键a的值为string类型的3。 redis 127.0.0.1:6379> set a 3 QUEUED #从键a所关联的值的头部弹出元素,由于该值是字符串类型,而lpop命令仅能用于List类型,因此在执行exec命令时,该命令将会失败。 redis 127.0.0.1:6379> lpop a QUEUED #再次设置键a的值为字符串4。 redis 127.0.0.1:6379> set a 4 QUEUED #获取键a的值,以便确认该值是否被事务中的第二个set命令设置成功。 redis 127.0.0.1:6379> get a QUEUED #从结果中可以看出,事务中的第二条命令lpop执行失败,而其后的set和get命令均执行成功,这一点是Redis的事务与关系型数据库中的事务之间最为重要的差别。 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"
#为键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的值,从结果中可以看出该键的值仍为事务开始之前的值。 redis 127.0.0.1:6379> get t2 "tt"
4. WATCH command and CAS-based optimistic locking:
val = GET mykey val = val + 1 SET mykey $val
WATCH mykey val = GET mykey val = val + 1 MULTI SET mykey $val EXEC

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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

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.

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

Redis, as a message middleware, supports production-consumption models, can persist messages and ensure reliable delivery. Using Redis as the message middleware enables low latency, reliable and scalable messaging.

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.
