Welcome back! You've now learned how to build and execute basic transactions in Redis. 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 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. Here's a quick overview of what you will learn:
watch
: Understanding the importance of monitoring keys to control transaction execution.watch
to implement safer and more conditional updates to your Redis data.Let's take a look at a practical example of how to use watch
in your code.
JavaScript1import { createClient } from 'redis'; 2 3const client = createClient(); 4 5client.on('error', console.error); 6await client.connect(); 7 8async function updateBalance(userId, increment) { 9 while (true) { 10 try { 11 await client.watch(`balance:${userId}`); 12 const balance = parseInt(await client.get(`balance:${userId}`), 10) || 0; 13 14 const pipeline = client.multi(); 15 pipeline.set(`balance:${userId}`, balance + increment); 16 17 const result = await pipeline.exec(); 18 if (result) break; 19 } catch (err) { 20 if (err.message === 'EXECABORT Transaction discarded because of previous errors.') { 21 console.log('Retrying transaction:', err.message); 22 continue; 23 } else { 24 throw err; 25 } 26 } 27 } 28} 29 30await client.set('balance:1', 100); 31await updateBalance(1, 50); 32 33const updatedBalance = await client.get('balance:1'); 34console.log(`Updated balance for user 1: ${updatedBalance}`); 35 36await client.disconnect();
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 pipeline.exec()
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 function, updateBalance
, that takes the userId
and increment
as arguments.
client.multi()
to execute multiple commands in a single transaction.while
loop, we use the watch
command to monitor the balance:{userId}
key and ensure that no other client modifies it during the transaction.client.get()
and set it to 0
if it doesn't exist.increment
value to the current balance.pipeline.exec()
command executes the transaction.catch
block and the continue
statement.Now let's understand how the function is used:
1
to 100
.updateBalance
function with userId=1
and increment=50
to increase the balance by 50
.1
and print it.Mastering the watch
command is critical for a few important reasons:
watch
ensures that actions only occur if certain conditions are met, allowing for safer updates.watch
helps avoid conflicts and manage errors when multiple clients are trying to update the same data.Utilizing watch
effectively enables you to write more robust and reliable applications, safeguarding against potential race conditions and ensuring that concurrent updates do not interfere with each other.
Ready to get hands-on and explore further? Let's move on to the practice section and apply these commands in various scenarios to solidify your understanding.