Introduction to Watch in Redis
Introduction to Watch in Redis
Welcome back! In previous lessons, you've learned how to build and execute transactions in Redis using PHP with the Predis library. This lesson will introduce you to the watch functionality in 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. The lesson will focus on understanding how to monitor keys to control transaction execution.
Using "watch" with Predis
Below is a code example of how to use the watch command with Predis:
The example code demonstrates how to use the watch command. Here's a detailed explanation:
-
Setup: The code begins by loading the Predis library with
require 'vendor/autoload.php';. Two Redis clients are then created usingPredis\Client. These simulate concurrent access to Redis. -
Key Initialization: Two keys,
$keyand$anotherKey, are initialized with the value0. These keys simulate data fields within Redis that are subject to transactions. -
Watch Command: The primary client initiates a
watchon the key$keyusing$client->watch($key);. This instructs Redis to monitor this specific key for changes. -
Start Transaction: A transaction block is started by invoking
$client->multi();. This allows all subsequent commands to be queued and executed as a single transaction. -
Increment Operations: Both keys are incremented by
50using$client->incrby($key, 50);and$client->incrby($anotherKey, 50);. These commands are queued for transaction execution. -
Concurrent Modification: A simulated concurrent client (
$otherClient) modifies the watched key,$key, by23using$otherClient->incrby($key, 23);. -
Additional Increment: The primary client again queues increment commands for both keys with an additional
50. -
Execute and Check: When
$client->exec();is called, the transaction attempts to execute but fails to apply changes to$keybecause it was altered by another client during the transaction. Note that even though the value under$anotherKeywasn't subject to thewatchcommand, it still didn't get updated by the calls done within a transaction. -
Output: The final output shows that
$keyhas a value of23(from the concurrent modification), whereas$anotherKeyremains at0, reflecting the rollback of changes due to the watched condition.
This code illustrates the power of the watch command to maintain data integrity by acknowledging concurrent data modifications, effectively preventing conflicts in a multi-client environment.
