Python3 实现 Redis 消息队列

废话不多说,我们先封装一个类。

redis_message_queue.py

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from redis import Redis, ConnectionPool


class RMQ(object):

    def __init__(self, url, name):
        # self.client = Redis(host=url)
        pool = ConnectionPool.from_url(url=url, decode_responses=True)
        self.client = Redis(connection_pool=pool)
        self.queue_name = name

    def publish(self, data):
    	""" 发布 """
        self.client.publish(self.queue_name, data)
        return True

    def subscribe(self):
    	""" 订阅 """
        pub = self.client.pubsub()
        pub.subscribe(self.queue_name)
        return pub

    def run_subscribe(self):
    	""" 启动订阅 """
        pub = self.subscribe()
        while True:
            _, queue_name, message = pub.parse_response()
            if _ == 'subscribe':
                print('... 队列启动,开始接受消息 ...')
                continue
            data = {'queue': queue_name, 'message': message}
            print(data)

publish.py

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from redis_message_queue import RMQ

rmq = RMQ(url='redis://127.0.0.1:6379/15', name='main')


if __name__ == '__main__':
    print(rmq.publish('Nice!'))

执行结果:

(demo) MacBook:zhangyi$ python publish.py 
True
(demo) MacBook: zhangyi$

subscribe.py

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from redis_message_queue import RMQ

rmq = RMQ(url='redis://127.0.0.1:6379/15', name='main')


if __name__ == '__main__':
    rmq.run_subscribe()

执行结果:

(demo) MacBook:zhangyi$ python subscribe.py 
... 队列启动,开始接受消息 ...
{'queue': 'main', 'message': 'Nice!'}
参考文章:https://segmentfault.com/a/1190000016898228

你可能感兴趣的:(#,Python,队列,redis,python)