Transactions
Each Redis command runs atomically by itself. But what if you need to combine several commands into an atomic block (transaction), which either all get executed atomically or none? And what if you need to evaluate some data in your application in the middle?
This is typically solved using Redis' transaction
commands WATCH, MULTI, EXEC.
The nice thing about kotlin-redis is that you can combine transaction with pipelines, both for watching/reading data and for writing.
To use Redis transactions, use the conn.pipeline {} API for watching and
reading data and conn.transactionPipeline {} for writing.
Example 1 - Get-then-act transaction using 2 round trips on a single connection:
// round trip 1: watch and get
val (key1Value, key2Value) = conn.watchAndGet("key1", "key2")
// eval results in code, decide what to do
// here we just postfix with -2
val key1NewValue = "$key1Value-2"
val key2NewValue = "$key2Value-2"
// round trip 2: multi + set + set + exec
val (txSuccess, _) = conn.transactionPipeline {
set("key1", key1NewValue)
set("key2", key2NewValue)
}