【问题标题】:Store local intermediate result of 'rpop' in redis lua script在redis lua脚本中存储'rpop'的本地中间结果
【发布时间】:2020-11-25 18:55:04
【问题描述】:
        # Check processing queue for any previously unprocessed items.
        # If previously unprocessed item
        # Check if item key is not expired and push back to processing queue
        # Otherwise push back onto work queue
        # (May want to r_push if we need immediate processing)
        lua_script = f"""
            local saved_item = redis.call('rpop', 'processing_list')

            if (saved_item ~= nil) then
                if (redis.call('exists', 'processing_list' .. _ .. saved_item) == 1) then
                    redis.call('lpush', 'processing_list', saved_item)
                else
                    redis.call('lpush', 'work_list', saved_item)
                end
            end
        """
        self._queue_client.get_redis_client().eval(lua_script, 0)

上面我正在尝试使用 redis 实现一个持久队列。我需要这部分逻辑是原子的,但是看到 redis 事务不允许中间读取和写入,我不得不求助于 lua。问题是最初的“rpop”行不起作用。我在我的 redis-cli 中验证它返回 (nil),因此永远不会正确设置“saved_item”变量。有没有更好的方法来完成中间读取,然后使用该值进行条件逻辑?

【问题讨论】:

  • 您不认为您在与预期不同的 Redis 列表上执行 rpop 吗?
  • 是的,这就是目的。有一个“处理”队列和一个“工作”队列以及一个处理到期密钥。实现redis持久队列。不过,我确实找到了解决方案。见下文。

标签: python redis lua queue


【解决方案1】:

作为 lua 的新手,我不得不破解它直到它起作用,但仍然没有弄清楚为什么没有梳理 lua 文档。关键是创建一个本地函数以从中返回 rpop 项目并将其存储在本地变量中,而不是直接尝试。与 Lua 返回值有关。

        lua_script = f"""
        if (redis.call('exists', '{self._processing_queue_name}') == 1) then
            local rpop = function (list) return redis.call('rpop', list) end
            local saved_item = rpop('{self._processing_queue_name}')

            if (saved_item ~= nil) then
                if (redis.call('exists', '{self._processing_queue_name}' .. '_' .. saved_item) == 1) then
                    redis.call('lpush', '{self._processing_queue_name}', saved_item)
                else
                    redis.call('lpush', '{self._queue_name}', saved_item)
                end
            end
        end
    """

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多