w3resource

Redis Transactions: WATCH key [key ...]

Redis WATCH Command

Redis WATCH command is used to mark the given keys to be watched for conditional execution of a transaction.

Here are some common uses and scenarios for the "WATCH" command:

  • Conditional Execution: Monitors one or more keys for changes, allowing the transaction to proceed only if these keys remain unchanged.
  • Optimistic Locking: Implements optimistic locking by tracking key modifications to ensure transaction integrity before committing.
  • Prevent Data Conflicts: Helps prevent conflicts and ensures that transactions are applied only if no other client has modified the watched keys.
  • Transaction Validation: Provides a mechanism to validate that watched keys have not been altered since the transaction began, enabling safe execution of transactional commands.

Syntax:

WATCH key [key ...] 

Available since

2.2.0.

Return Value

Simple string reply: always OK.

Return Value Type

String

Example:

127.0.0.1:6379> WATCH zset
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> ZREM zset element
QUEUED
127.0.0.1:6379> EXEC
1) (integer) 0

Previous: UNWATCH
Next: Redis Scripting EVAL



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/redis/redis-watch-key.php