Atomic Getset on a Hash in Redis

I am going to store a hit counter for multiple URLs in Redis. I plan to use hash because it makes sense. It also has an atomic increment function, which is crucial for my use.

Each time so, I am going to aggregate the number of hits on the URL in another data store. For this purpose, I would like to get a hit counter and reset back to zero. I can't seem to find an operation like GETSET that works with hashes. If I write down hits between getting the hit score and resetting it to zero, it will be lost without any atomic operation.

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

+7
source share
1 answer

Try looking at redis transactions docs, namely a combination of the WATCH and MULTI commands:

WATCHed keys are observed to detect changes in them. If at least one observed key is changed before the EXEC command, the whole transactional interruption, and EXEC returns a zero multivariate response to inform that the transaction failed.

...

So what is a WATCH? This is the command that makes the EXEC clause conditional: we ask Redis to execute the transaction only if no other client has WATCHed keys. Otherwise, the transaction is not entered at all.

+6
source

All Articles