【问题标题】:Storing huge randomized list of similar items in Redis在 Redis 中存储大量类似项目的随机列表
【发布时间】:2011-02-25 04:14:07
【问题描述】:

Redis 2.0.3

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

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

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

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

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

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

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

有什么提示吗?

【问题讨论】:

    标签: redis data-storage high-load


    【解决方案1】:

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

    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,可能会遗漏一些明显的东西。

    我怀疑insert_items()中的LOCK/UNLOCK可能是多余的,可以替换为MULTI/EXEC,但我认为LOCK/UNLOCK中需要它987654331@ 正常工作(我不知道如何替换为MULTI/EXEC)...

    【讨论】:

    • 请注意,这里的概率是有偏差的,因为相同物品的数量对获得该物品的机会没有任何影响。这适用于我的特定用例。
    • 在 2.2 上更好的方法是使用 WATCH:stackoverflow.com/questions/5118807/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多