Reputation: 1844
Working in an application that stores entities in redis as a serialized binary blob. I have multiple clients working on the same data set and I wish to use optimistic concurrency.
My requirements are these:
Is this possible to do in redis? And if so: what redis commands should be executed to do this?
Upvotes: 8
Views: 12439
Reputation: 19330
With a credit to my boss, who invented it and I executed StackExchange.Redis
implementation of reliable concurrency. This is an example of checking if adding items to RedisSet
has been completed
Scenario: you need to process a batch of items in different processes. When batch is complete, you want only one single thread report this completion. In this scenario I use Set
to keep adding the items. Once Set
is filled, I need to report this once.
public bool HasComletedRedisSet(string value, long expected)
{
long actualCount = 0;
bool added = _db.SetAdd("key1", value);
if (added)
{
actualCount = _db.StringIncrement("key2", 1L);
}
return (actualCount == expectedTotalCount);
}
This code is reliably concurrent and only 1 time returns true
... without transaction.
When working with Redis concurrency, one might try think about negative scenarios...
Upvotes: 0
Reputation: 149
For anyone using the StackExchange.Redis library, keep in mind that it multiplexes a single connection and the check-and-set pattern described above may not work as expected for 2 requests sharing that connection. See this article in the docs: link
Upvotes: 1
Reputation: 39558
WATCH key
, GET key
, MULTI
, SET key
, then EXEC
. The EXEC
will fail if the key's value has changed since you executed the WATCH
.
http://redis.io/topics/transactions#cas
Upvotes: 16