python redis中blpop和lpop的区别

python redis中lpop()方法是获取并删除左边第一个对象。

    def lpop(
        self,
        name: str,
        count: Optional[int] = None,
    ) -> Union[Awaitable[Union[str, List, None]], Union[str, List, None]]:
        """
        Removes and returns the first elements of the list ``name``.

        By default, the command pops a single element from the beginning of
        the list. When provided with the optional ``count`` argument, the reply
        will consist of up to count elements, depending on the list's length.

        For more information see https://redis.io/commands/lpop
        """

 python redis中blpop()方法是获取并删除左边第一个对象,并多了一个阻塞的作用(如果传入的timeout参数大于零,执行blpop()是会检查集合里面有没有对象,没有对象则进行阻塞timeout秒,如果timeout为0或者不传则无期限代码阻塞,直到有新的对象加入到集合)。


    def blpop(
        self, keys: List, timeout: Optional[int] = 0
    ) -> Union[Awaitable[list], list]:
        """
        LPOP a value off of the first non-empty list
        named in the ``keys`` list.

        If none of the lists in ``keys`` has a value to LPOP, then block
        for ``timeout`` seconds, or until a value gets pushed on to one
        of the lists.

        If timeout is 0, then block indefinitely.

        For more information see https://redis.io/commands/blpop
        """

测试lpop()方法:

import redis
import time



if __name__ == "__main__":
    # 使用连接池来管理多个连接
    pool = redis.ConnectionPool(host='127.0.0.1', port=6379,password="123456", db=0)
    redis_client = redis.StrictRedis(connection_pool=pool)



    while True:
        #获取消息队列
        print("读取mq队列")
        task = redis_client.lpop("task")

        if task is not None:
            print("收到消息: " + str(task))
            #执行任务

        time.sleep(1)

结果每秒会获取一次:

测试blpop()方法:

import redis
import time

if __name__ == "__main__":
    # 使用连接池来管理多个连接
    pool = redis.ConnectionPool(host='127.0.0.1', port=6379,password="123456", db=0)
    redis_client = redis.StrictRedis(connection_pool=pool)

    while True:
        #获取消息队列
        print("读取mq队列")
        task = redis_client.blpop(_task")

        if task is not None:
            print("收到消息: " + str(task))
            #执行任务

        time.sleep(1)

结果只读取一次,然后就阻塞了:

直到有对象进入集合,才会继续执行代码。

import redis


if __name__ == "__main__":
    # 使用连接池来管理多个连接
    pool = redis.ConnectionPool(host='127.0.0.1', port=6379,password="123456", db=0)
    redis_client = redis.StrictRedis(connection_pool=pool)

    # 设置键值对
    redis_client.rpush("task","22")

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值