如果另一个键中的计数器低于零,则从集合中原子地删除一个项目? [英] Atomically remove an item from set if a counter in another key is below zero?

查看:55
本文介绍了如果另一个键中的计数器低于零,则从集合中原子地删除一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Redis 2.0.3

Redis 2.0.3

在我的 Redis 数据库中,我有一组项目.每个项目都有一个与之关联的计数器:

In my Redis DB I have a set of items. Each item has a counter, associated with it:

MULTI
    SADD "items-set" "foo"
    INCRBY "items:foo" 10000
EXEC

新项目以随机间隔添加到集合中.

New items are added to the set at random intervals.

当用户执行某个动作时,计数器递减:

When user does a certain action, counter is decremented:

new_counter = DECR "items:foo"

当计数器降到零以下时,我需要从集合中原子地删除项目(或者:当计数器准确地达到零时,我可以为此修复逻辑.)

I need to atomically remove the item from the set, when the counter drops below zero (alternatively: when the counter reaches zero exactly, I can fix up logic for that.)

if new_counter < 0 then
    MULTI
        SREM "items-set" "foo"
        DEL "items:foo"
    EXEC
end

如何在不使用 SETNX/GETSET 锁定项目名称的情况下执行此操作?

How can I do this without locking by the item name with SETNX/GETSET?

涉及更改我在 Redis 中存储数据的方式的解决方案是可以接受的.(但是,为了以防万一,我保留用一些我可能会在初始文本中遗漏的特定于任务的细节来反驳它们的权利.)

Solutions, involving change of the way I store data in Redis, are acceptable. (But, just in case, I reserve a right to counter them with some task-specific detail that I could miss in initial text.)

推荐答案

只需使用 Redis 2.2 新的 WATCH 功能:

just use the new WATCH capability of Redis 2.2:

WATCH items-set items:foo
count = GET items:foo
IF count == 0:
    MULTI
    SREM items-set foo
    SET items:foo count-1
    EXEC
ELSE:
    MULTI
    SET items:foo count-1
    EXEC

要理解示例,您需要了解 WATCH 的工作原理.请查看 http://redis.io 网站上的文档.

To understand the example you need to understand how WATCH works. Please check the doc at http://redis.io site.

附言Redis 2.0.3 没有办法做到这一点

p.s. there are no ways to do this with Redis 2.0.3

这篇关于如果另一个键中的计数器低于零,则从集合中原子地删除一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆