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]
-
1Wrap it in a transaction?apokryfos– apokryfos2016-11-16 14:56:21 +00:00Commented Nov 16, 2016 at 14:56
-
1rediscookbook.org/get_and_delete.html should work with StackExchange.Redis as well.Christian.K– Christian.K2016-11-16 14:57:42 +00:00Commented Nov 16, 2016 at 14:57
-
@apokryfos Exactly! Good point! Thanks!Ben– Ben2016-11-16 15:05:57 +00:00Commented 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).Ben– Ben2016-11-16 15:07:08 +00:00Commented Nov 16, 2016 at 15:07
Add a comment
|
1 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
3 Comments
thepirat000
If your key is a list, you should probably change the call to
tran.ListRangeAsyncBen
That's exactly what I should do!
adinas
@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?