0

Redis 2.0.3

我需要在 Redis 中存储大量项目。每个项目都是一个短字符串(少于 256 个字符)。

我需要对列表做两个操作:

  • 添加许多(几千到一百万)相同的项目。(一天几次)

  • 从列表中随机删除一项。没有必要有“公平”的随机性。任何“足够好”的方法都可以。(每秒最多数百次)

我没有足够的 RAM 将所有项目一一存储在列表中。

我认为我需要分批存放物品,名称和柜台。(将有多达数千个不同的项目,更多的是数百个。)

但我不确定如何有效地组织这个。

有什么提示吗?

4

1 回答 1

0

好吧,既然没有人愿意帮助我,这里有一个“愚蠢”的解决方案,用伪代码表示。

  1. 获取随机元素:

    function maybe_get_next_item()
      item_name = SRANDMEMBER "items-set"
      item_key = "items:" + item_name
    
      new_item_count = DECR (item_key)
    
      if new_item_count < 0 then
        LOCK -- As explained in SETNX docs
          new_item_count = GET (item_key) -- More added while we were locking?
          if new_item_count and new_item_count < 0 then
            SREM (item_name) -- No, expire it
          end
        UNLOCK
      end
    
      if new_item_count and new_item_count >= 0 then
        return item_name
      end
    
      return false -- this item not found
    end
    
    function get_next_item()
      item_name = maybe_get_next_item()
      while not item_name and (SCARD "items-set" > 0) do
        item_name = maybe_get_next_item()
      end
      return item_name -- false if all items are expended
    end
    
  2. 插入新元素

    function insert_items(item_name, amount)
      LOCK -- As explained in SETNX docs
        SADD "items-set" (item_name)
        INCRBY ("items:" + item_name) amount
      UNLOCK
    end
    

如果存在,请建议一个更好的解决方案,我仍在摸索 Redis,可能会错过一些明显的东西。

我怀疑LOCK/ UNLOCKininsert_items()可能是多余的,可以用MULTI/代替EXEC,但我认为LOCK/ UNLOCKin需要它maybe_get_next_item()才能正常工作(我不知道如何用MULTI/代替EXEC)......

于 2011-02-25T14:52:16.400 回答