开发者

Atomic GETSET on a hash in Redis

开发者 https://www.devze.com 2023-04-12 06:13 出处:网络
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 u

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 p开发者_Python百科rovides a hash itself.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号