Ben Ben - 18 days ago 9
C# Question

Atomic read and delete from Redis using StackExchange.Redis

Is there an easy way to atomically read a value and then delete it from Redis using StackExchange c# driver?

I am buffering items in Redis and when they reach a certain threshold I retrieve them, but I also want to flush my buffer.
I need to mention that I store items in a list and by "flushing the buffer" I mean I want to delete the list.

"key" : [list of items]

Answer

You can create a transaction and do the GET/DEL atomically, like this:

var db = connectionMultiplexer.GetDatabase();
var tran = db.CreateTransaction();
var getResult = tran.StringGetAsync(key);
tran.KeyDeleteAsync(key);
tran.Execute();
var value = getResult.Result;

This will send the following commands to Redis:

MULTI
GET "key"
DEL "key"
EXEC
Comments