Redis Transactions

In this article you are going to learn about Redis Transactions. It is useful when you either want to perform all the transactions or you want to rollback everything. This feature is almost present in all the databases.

Below Commands are the basic building blocks of Redis Transactions.


What are the key properties of Transactions?

Transactions guarantee that they are executed in sequence.

Either all commands are processed or none are processed.

127.0.0.1:6379> keys *
1) "ticket_available"
127.0.0.1:6379> multi
OK
127.0.0.1:6379> get ticket_available
QUEUED
127.0.0.1:6379> decr ticket_available
QUEUED
127.0.0.1:6379> exec
1) "3"
2) (integer) 2
127.0.0.1:6379>

If Error Occurs then Transaction is aborted


127.0.0.1:6379> keys *
1) "ticket_available"
127.0.0.1:6379> multi
OK
127.0.0.1:6379> ticket_available
(error) ERR unknown command `ticket_available`, with args beginning with:
127.0.0.1:6379> get ticket_available
QUEUED
127.0.0.1:6379> decr ticket_available
QUEUED
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379>


Discarding a Transaction

127.0.0.1:6379> multi
OK
127.0.0.1:6379> get ticket_available
QUEUED
127.0.0.1:6379> incr ticket_available
QUEUED
127.0.0.1:6379> discard
OK
127.0.0.1:6379> get ticket_available
"2"
127.0.0.1:6379>

 

“Watch” Redis Keys during Transaction , Fail if value changes.


127.0.0.1:6379> watch ticket_available
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> get ticket_available
QUEUED
127.0.0.1:6379> decr ticket_available
QUEUED
127.0.0.1:6379> exec
(nil)

Read more about Redis Here.

You may also consider subscribing to my Youtube Channel here.

Leave a Comment

Subscribe to our newsletter for weekly tips.

Thanks for Subscribing to Newsletter.

There was an error while trying to send your request. Please try again.

IT Panther will use the information you provide on this form to be in touch with you and to provide updates and marketing.
%d bloggers like this: