import time
from threading import Thread
from redis import Redis, ConnectionPool
import random
class MQS(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) #订阅指定队列
# print('... 队列启动,开始接受消息...')
while True:
_, queue_name, message = pub.parse_response()#订阅的响应实体
if _ == 'subscribe':
print('... 队列启动,开始接受消息...')
continue
data = {'queue=': queue_name, 'message=': message}
print('订阅消息实体=',data)
rmq = MQS(url='redis://127.0.0.1:6379/15', name='获取产品队列消息')
class Subscribe(Thread): # 订阅线程类
def run(self):
# print('name='+self.name)
rmq.subscribe() # 线程1先启动订阅,不能睡眠,只要有新消息立即读取到
class Publish(Thread): # 发布线程类
def run(self):
for i in range(10):
t = random.randint(1, 5)
time.sleep(t)
rmq.publish('hello,Nice!发布最新消息ID=' + str(i)) # 发布信息,在订阅中获取该消息
if __name__ == '__main__':
for i in range(1):
p = Subscribe()
p.start() # 启动订阅者线程
for i in range(100):
c = Publish()
c.start() # 启动发布者线程