search
HomeBackend DevelopmentC#.Net TutorialRedis 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"


3. Rollback transaction:
 #为键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:


## In Redis transaction, WATCH command Can be used to provide CAS (check-and-set) functionality. 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 (race condition). For example, both clients A and B 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 value of mykey to be lost. The result is 11, not 12 as we thought. 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 key through the WATCH command before obtaining the value of mykey, and then The set command is also surrounded by a transaction, which can effectively ensure that before each connection executes EXEC, if the value of mykey obtained by the current connection is modified by other connected clients, the EXEC command of the current connection will fail to execute. In this way, the caller can know whether val has been successfully reset after judging the return value.

The above is the content of Redis Tutorial (8): Detailed Transactions. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement
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
Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

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.