6

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]

4
  • 1
    Wrap it in a transaction? Commented Nov 16, 2016 at 14:56
  • 1
    rediscookbook.org/get_and_delete.html should work with StackExchange.Redis as well. Commented Nov 16, 2016 at 14:57
  • @apokryfos Exactly! Good point! Thanks! Commented Nov 16, 2016 at 15:05
  • @Christian.K I read that one, but I was wondering if there's an out of the box method or something in the API ( since it's been officially a few hours I am working with StackExchange driver and Redis for that matter). Commented Nov 16, 2016 at 15:07

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

3 Comments

If your key is a list, you should probably change the call to tran.ListRangeAsync
That's exactly what I should do!
@thepirat000 , If multiple apps (or the same app on multiple servers) are making this request to Redis. Will this code make sure only one will succeed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.