Conteúdo do Curso
Introduction to Redis
Introduction to Redis
Transactions
All commands within the transaction are executed simultaneously. If one of the commands fails, none of them will be executed. This ensures data consistency by preventing partial or invalid changes, even if errors occur.
How Transactions Are Used
Transactions are commonly applied when multiple operations on data must be performed together, such as incrementing a counter and writing related data to another key. Using transactions ensures that either all operations are completed, or none are, maintaining data integrity.
Core Commands for Transactions
To start a transaction in Redis, use the MULTI
command. This informs Redis that all subsequent commands should be part of the transaction.
Once you issue MULTI
, Redis queues the commands you want to include in the transaction.
In this example, the commands SET key1 "value1"
and SET key2 "value2"
are not executed immediately. Instead, they are added to the transaction queue and executed together when the EXEC
command is called.
Executing a Transaction
To execute all the commands in the transaction, use the EXEC
command. This runs every queued command in the transaction.
After calling EXEC
, both SET
operations will be performed.
Cancelling a Transaction
If you decide to cancel a transaction before execution, use the DISCARD
command. This clears all the commands in the transaction queue, ensuring they will not be executed.
After calling DISCARD
, all the commands added to the transaction since MULTI
will be discarded and not executed.
Monitoring Keys During a Transaction
During a transaction, commands are queued but not executed immediately. The WATCH
command can be used to monitor specific keys. If any of these keys are modified before the transaction is executed, the transaction will be aborted to prevent data conflicts.
In this example, if the value of key1
changes before the EXEC
command is called, the transaction will not be executed. This ensures data consistency, especially when multiple clients attempt to modify the same key simultaneously.
1. What happens if one of the commands in a Redis transaction fails?
2. Which command should be used to start a Redis transaction?
Obrigado pelo seu feedback!