【问题标题】:the redis stream length limit not work when using python redis使用 python redis 时,redis 流长度限制不起作用
【发布时间】:2021-05-14 06:13:15
【问题描述】:

现在我正在使用 python(Python 3) redis 客户端将元素添加到 redis 流中,这是 lib 的依赖项:

redis~=5.0.3

然后这是我使用 Python 将元素写入 redis 的代码:

def push_message_to_stream(article):
    try:
        message = {
            "id": article.id,
            "sub_source_id": article.sub_source_id
        }
        #
        # Redis did not remove the ack message automatic
        # when the element is full, it remove the oldest
        #
        redis_client.xadd(name=article_stream_name, fields=message, maxlen=10)
        # redis_client.xgroup_create(name=article_stream_name, groupname=article_group_name)
        # redis_client.publish(channel=article_stream_name, message="hello world!")
    except Exception as e:
        logger.error("write stream error:", e)

该元素可以成功写入redis,但是在我将maxlen的参数添加到10之后,当我检查redis中的流元素时,流中仍然有90多个元素,我猜测可能是redis使用旧的创建者配置,然后我尝试删除流并重新创建它,但仍然在这种情况下,我在哪里做错了?为什么maxlen参数没有生效?

【问题讨论】:

    标签: python redis


    【解决方案1】:

    默认情况下,redis-pyxaddapproximate 参数设置为 True。这意味着您不会获得精确的长度修剪,并为您提供更好的性能。如果您想要确切的长度,请尝试:

    redis_client.xadd(name=article_stream_name, fields=message, maxlen=10, approximate=False)
    

    xadd的源代码:https://redis-py.readthedocs.io/en/stable/_modules/redis/client.html#Redis.xadd

    【讨论】:

    • 近似参数默认为True,表示当流长度大于10时redis不会立即修剪流,但可以获得更好的性能。如果设置为 False,它将立即修剪流,但性能较低。对吗?@Simon Prickett
    • @Dolphin 在任何一种情况下都会立即修剪,但当该参数为 True 时会修剪到近似数字。它是近似的,因为它删除了底层数据结构树中最接近的整个节点,该节点删除了所需数量的条目,而不是通过树进行解析,直到找到确切的数字,这会降低性能。
    猜你喜欢
    • 2012-08-17
    • 2019-08-16
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    相关资源
    最近更新 更多