Implementing Conditional Transactions in Go with Redis `Watch`
Introduction to Watch in Redis
Welcome back! You’ve learned how to build and execute basic transactions in Redis using Go. This lesson will introduce you to the watch functionality in go-redis, enabling conditional and controlled transactions. Such functionality is vital for scenarios where you need to monitor specific keys and ensure operations only execute when certain conditions are met.
What You'll Learn
In this unit, you will explore the Watch feature in Redis using the go-redis library in Go. Here's a quick overview of your learning objectives:
- Setting Up
Watch: Understanding how to monitor keys to control transaction execution in Go. - Implementing Conditional Updates: Crafting functions that use
Watchto deliver safer and more conditional updates to your Redis data with Go.
Let's take a look at a practical example of how to use Watch in your code.
In this Go example, we watch the balance:id key to catch changes. If another client alters the value before executing the transaction, the transaction will fail, and we retry. This ensures balance updates are consistent.
Let's break down each step in the code snippet:
- We define a function
updateBalancethat takes the Redis client, context,userID, andincrementas arguments.- We begin by using
Watchto keep an eye on thebalance:idkey, ensuring no modifications during the transaction. - The current balance value is retrieved using
Get, and defaults to0if nonexistent. - We use
TxPipelinedto run commands in a transaction safely. - We update the balance by adding the
incrementvalue. - If the operation fails due to a change in the balance key, the transaction is retried.
- We begin by using
By calling updateBalance, we adjust userID=1's balance by 50 and print the updated value.
