Yes, Redis supports transactions via the MULTI/EXEC commands. Transactions in Redis are used to group a set of commands together, which can be executed atomically as a single transaction.
The basic syntax for a Redis transaction is as follows:
MULTI <commands> EXEC
Here's an example of how a transaction would work in Redis:
In this example, we're setting two keys (
key2) to two values (
value2). These commands are grouped together inside the transaction block (
EXEC) and will be executed atomically.
Redis also provides a feature called WATCH, which allows you to ensure that a transaction executes only if specific conditions (such as a particular value of a key) are met. Here's an example of using WATCH with a transaction:
In this example, we're incrementing the value of
key1 by one, but only if it hasn't been modified by another client while we were executing the transaction. The
WATCH command tells Redis to monitor changes to
key1, and the transaction block will only execute if
key1 has not been modified since the
WATCH command was issued.
Transactions in Redis provide a powerful way to atomically execute multiple commands, ensuring consistency and reliability in your database operations.