【Python】使用 Python 中的 aioredis 实现后进先出队列

引言

在现代的分布式系统中,使用消息队列是一种常见的方式来实现异步通信和任务处理。Redis 是一种流行的内存数据库,它的列表数据结构非常适合用作消息队列。本文将介绍如何使用 Python 和 aioredis 库来连接 Redis 数据库,并实现一个基于 Redis 的连接池和一个后进先出队列。

python 复制代码
import aioredis


class RedisPool:
    _instances = {}
    def __new__(cls, redisURL):
        if redisURL not in cls._instances:
            cls._instances[redisURL] = super().__new__(cls)
            cls._instances[redisURL]._pool = None
            return cls._instances[redisURL]
        else:
            raise cls._instances[redisURL]

    def __init__(self, redisURL):
        self._pool = None
        self.redisURL = redisURL

    async def get_pool(self):
        if self._pool is None:
            self._pool = await aioredis.from_url(self.redisURL)
        return self._pool

class RedisQueue:
    def __init__(self, redisPool, queueName):
        self._pool = redisPool
        self._queueName = queueName

    async def push(self, data):
        pool = await self._pool.get_pool()
        await pool.lpush(self._queueName, data)

    async def pop(self):
        pool = await self._pool.get_pool()
        return await pool.lpop(self._queueName)

    async def size(self):
        pool = await self._pool.get_pool()
        return await pool.llen(self._queueName)


async def main():
    # 带密码的redis redis://:password@localhost:6379/0
    redisPool = RedisPool('redis://:password@233.233.233.233:33333/0')
    queue = RedisQueue(redisPool, 'testQueue')

    for i in range(10):
        print(f"push {i}")
        await queue.push(str(i))
    print(f"size {await queue.size()}")
    for i in range(10):
        print(await queue.pop())
    print(f"size {await queue.size()}")


if __name__ == '__main__':
    import asyncio
    asyncio.run(main())
相关推荐
代码民工正电荷7 小时前
JAVA重要知识点和集合
java·开发语言
星恒随风7 小时前
C++11 加餐(4)并发支持库——condition_variable 条件变量与生产者消费者模型
开发语言·c++
利威尔xu7 小时前
Go map 并发十连问:多 goroutine 同时读写触发 fatal error,进程直接崩溃
开发语言·golang
钱栈up7 小时前
长安汽车把海外年销钉在100万辆,2030年要翻到200万——出海从故事变成基建
爬虫·python·数据分析
你不知道我是谁?7 小时前
GESP C++ 补充知识:浮点数格式化输出(%f/%e/%g)与 fmod 浮点余数实战
开发语言·c++
富贵儿9987 小时前
NL2SQL 实践手记 03:让模型决定下一步——把 Workflow 改造成 SQL Agent
数据库·python·sql·ai·自然语言处理·langchain
九蝶科技7 小时前
运费分摊的二开实现:BigDecimal 精确分摊 + 尾差补齐 + 暂估调整
开发语言·python
Ryan-Zhong8 小时前
一次接入 16 个平台:视频链接元数据解析 API 的 Python 实战与踩坑记录
开发语言·python·dreamweaver
无限聚核9 小时前
PHP 对接美团、抖音团购核销接口:预核销、核销、重试和撤销一份代码跑通,无限聚核
开发语言·php·美团·团购核销接口
aihuge202611 小时前
RAG 检索要不要加缓存:同查询二次命中省一次计算,语料一变就得失效
python·大模型·rag