一个简单的消息队列

目录

原理

实现代码

示例


原理

消息队列是一个先进先出栈,每次都处理第一项,处理完了过后会删除这个消息,这是一个简单的消息队列图:

实现代码

首先消息队列需要一个队列,我们用Python里的列表:

python 复制代码
self.queue = []

接着我们要实现把一个消息加入队列和处理消息:

python 复制代码
def push(self, text):
    self.queue.append(text)

def pull(self):
    test = self.queue[0]
    self.queue.pop()
    return test

示例

然后我们来验证一下:

python 复制代码
import time

'''
消息队列的类
'''

mq = MessageQueue()
for i in range(1, 21):
    mq.push(f"[Error {i}] author is not find")
    print(mq.pull(), end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".")

结果:

Error 1\] author is not find... \[Error 2\] author is not find... \[Error 3\] author is not find... \[Error 4\] author is not find... \[Error 5\] author is not find... \[Error 6\] author is not find... \[Error 7\] author is not find... \[Error 8\] author is not find... \[Error 9\] author is not find... \[Error 10\] author is not find... \[Error 11\] author is not find... \[Error 12\] author is not find... \[Error 13\] author is not find... \[Error 14\] author is not find... \[Error 15\] author is not find... \[Error 16\] author is not find... \[Error 17\] author is not find... \[Error 18\] author is not find... \[Error 19\] author is not find... \[Error 20\] author is not find... Process finished with exit code 0

列表:

完整代码

python 复制代码
import time

class MessageQueue(object):
    def __init__(self):
        self.queue = []

    def push(self, text):
        self.queue.append(text)

    def pull(self):
        test = self.queue[0]
        self.queue.pop()
        return test

mq = MessageQueue()
for i in range(1, 21):
    mq.push(f"[Error {i}] author is not find")
    print(mq.pull(), end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".")
相关推荐
刘立军8 分钟前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机3 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i6 小时前
django中的FBV 和 CBV
python·django
c8i6 小时前
python中的闭包和装饰器
python
这里有鱼汤9 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩19 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python