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.
- , opens subtitles settings dialogsubtitles settings
- subtitles off
- , selectedEnglish Captions
- 2x
- 1.5x
- , selected1x
- 0.5x
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
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.
9123MULTISET key1 "value1"SET key2 "value2"
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.
EXEC
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.
DISCARD
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.
91234WATCH key1MULTISET key1 "new_value"EXEC
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?
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.