Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic GETSET on a hash in Redis

Tags:

atomic

redis

hash

I'm going to be storing a hit counter for a number of URLs in Redis. I'm planning on using a hash because that seems to make sense. It also has an atomic increment function which is critical to my use case.

Every so often, I'm going to aggregate the hit count per URL into another data store. For this purpose, I'd like to get the hit count and reset it back to zero. I can't seem to find an operation like GETSET that works on hashes. If I record a hit between getting the hit count and resetting it to zero, it will get lost without some kind of atomic operation.

Am I missing something? One alternative that occurred to me would be to hash the URL in my client (python) code and use the string commands, but that seems like a bit of a hack when Redis provides a hash itself.

like image 383
Edward Dale Avatar asked Oct 09 '11 09:10

Edward Dale


1 Answers

Try to look at redis transactions docs, namely the combination of WATCH and MULTI commands:

WATCHed keys are monitored in order to detect changes against them. If at least one watched key is modified before the EXEC command, the whole transaction aborts, and EXEC returns a Null multi-bulk reply to notify that the transaction failed.

...

So what is WATCH really about? It is a command that will make the EXEC conditional: we are asking Redis to perform the transaction only if no other client modified any of the WATCHed keys. Otherwise the transaction is not entered at all.

like image 160
yojimbo87 Avatar answered Sep 29 '22 19:09

yojimbo87