Welcome back! You’ve now learned how to build and execute basic transactions in Redis using StackExchange.Redis in C#. This next lesson takes you a step further by introducing the watch command. This command will help you implement more controlled and conditional transactions. They are essential for scenarios where you need to monitor certain keys and ensure that the operations are completed only when specific conditions are met.
In this unit, you will delve into the functionality of the watch command in Redis, utilizing C# and the StackExchange.Redis library. Here’s a quick overview of what you will learn:
- Setting Up
watch: Understand the importance of monitoring keys to control transaction execution. - Implementing Conditional Updates: Write functions that use
watchto implement safer and more conditional updates to your Redis data with C# syntax.
Let's take a look at a practical example of how to use watch in your C# code.
In this example, we start by watching the balance:{userId} key to monitor changes. If another client changes the value before you execute your transaction, the transaction Execute() will fail, and the transaction will retry. This ensures that your balance updates are consistent.
Let's break down each step in the code snippet:
- We define a method
UpdateBalancethat takes theuserIdandincrementas arguments.- We create a transaction using
db.CreateTransaction()to execute multiple commands in a single transaction. - Inside the
whileloop, we add a condition to monitor thebalance:{userId}key and ensure that no other client modifies it during the transaction. - We retrieve the current balance value using
db.StringGet()and set it to0if it doesn't exist. - We update the balance by adding the
incrementvalue to the current balance usingtran.StringSetAsync(). - The
tran.Execute()command executes the transaction. - If another client changes the balance key before the transaction is executed,
Execute()will returnfalse, and the transaction is retried.
- We create a transaction using
Now let's understand how the function is used:
- We set the initial balance for user
1to100. - We call the
UpdateBalancemethod withuserId="1"andincrement=50to increase the balance by50. - Finally, we retrieve the updated balance value for user
1and print it.
