Queueing More Commands and Executing the Transaction
In this step, you'll add more commands to the transaction queue and then execute the entire transaction using the EXEC
command.
Reconnect to the Redis server:
redis-cli
Since we have an existing transaction, we need to re-enter transaction mode:
MULTI
Now, let's queue a command to retrieve the value of mykey
:
GET mykey
You should see:
QUEUED
Next, let's add another command to set a different key, anotherkey
, with the value anothervalue
:
SET anotherkey "anothervalue"
The output should be:
QUEUED
Finally, let's queue an INCR
command to increment a counter named mycounter
. If mycounter
doesn't exist, Redis will create it and initialize it to 0 before incrementing:
INCR mycounter
You should see:
QUEUED
You've now queued several commands within the transaction. To execute them all at once, use the EXEC
command:
EXEC
The output should look similar to this:
1) OK
2) "myvalue"
3) OK
4) (integer) 1
Let's break down the output:
1) OK
: Result of the SET mykey "myvalue"
command.
2) "myvalue"
: Result of the GET mykey
command.
3) OK
: Result of the SET anotherkey "anothervalue"
command.
4) (integer) 1
: Result of the INCR mycounter
command.
All commands within the transaction were executed atomically.
Remember to exit the redis-cli
environment to ensure the command is logged:
exit