基于Redis做为消息中间件的代码封装,话不多说,直接上代码:
import json
import threading
try:
from redis import StrictRedis, ConnectionPool
except:
import os
os.system('pip install -i https://pypi.tuna.tsinghua.edu.cn/simple redis')
from redis import StrictRedis, ConnectionPool
def connect_redis(REDIS_HOST,REDIS_PORT,REDIS_DATABASE,REDIS_PWD):
import socket
#保持redis心跳的设置方式
pool = ConnectionPool(host=REDIS_HOST, port=REDIS_PORT,socket_keepalive=True,
socket_keepalive_options={socket.TCP_KEEPIDLE: 60, socket.TCP_KEEPINTVL: 30, socket.TCP_KEEPCNT: 3}
, db=REDIS_DATABASE, password=REDIS_PWD,decode_responses=True, encoding='UTF-8')
gl_Redis = StrictRedis(connection_pool=pool,decode_responses=True, charset='UTF-8', encoding='UTF-8')
try:
gl_Redis.ping()
msg = '【数据库:redis】 连接数据库成功...'
print(msg)
return gl_Redis
except TimeoutError:
msg = '【数据库:redis】 连接数据库失败...'
print(msg)
class RedisMQ():
def __init__(self,gl_Redis):
self.coon=gl_Redis
self.channels=[]
self.TOPIC_handler = {'test':print} # 主题处理程序
def publish(self,channel,message,):
'''发送消息,指定频道'''
print(channel,message,)
if isinstance(message,dict):
message = json.dumps(message)
try:
return self.coon.publish(channel,message),''
except Exception as e:
# print(str(e))
return False, str(e)
def subscribe(self,channel):
'''订阅单个频道'''
pub=self.coon.pubsub()
pub.subscribe(channel)
pub.parse_response()
self.channels.append(channel)
return pub
def psubscribe(self,channels):
'''订阅多个频道'''
pub=self.coon.pubsub()
pub.psubscribe(*channels)
pub.parse_response()
self.channels+=channels
return pub
def close(self):
self.conn.close()
def unsubscribe(self,channel):#取消订阅
self.coon.pubsub().unsubscribe(channel)
self.channels.remove(channel)
def continue_subscribe(self,channel):
'''持续监听单个频道,返回解析数据'''
r=self.subscribe(channel)
while True:
if not (msg:=r.parse_response()):
msg= {}
elif msg[0] == 'subscribe':
msg= {}
else:
msg=msg[-2:]
yield msg
def continue_psubscribe(self,channels):
'''持续监听多个频道,返回解析数据'''
r=self.psubscribe(channels)
while True:
if not (msg:=r.parse_response()):
msg=[]
elif msg[0] == 'psubscribe':
msg=[]
else:
msg=msg[-2:]
yield msg
# def recv_command(self,obj,TOPIC,handler) -> None:
# '''接收指令处理函数'''
# while True:
# # 解析数据-单次消费连接
# data = next(self.continue_subscribe(TOPIC))
# try:
# handler(obj,data)
# except Exception as e:
# print(e)
def recv_command(self,obj) -> None:
'''接收指令处理函数'''
channels = list(self.TOPIC_handler.keys())
if channels:
while True:
# 解析数据-单次消费连接
# data = next(self.continue_subscribe(TOPIC))
msg = next(self.continue_psubscribe(channels))
if msg:
channel, data = msg
handler = self.TOPIC_handler.get(channel,print)
try:
handler(obj,data)
except Exception as e:
print(e)
def listen(self,obj,TOPIC_handler:dict) -> bool:
try:
for TOPIC,handler in TOPIC_handler.items():
print(f'【监听】频道:{TOPIC},消息监听程序启动!')
# t3 = threading.Thread(target=self.recv_command,args=(obj,TOPIC,handler)) # 单次消费
t3 = threading.Thread(target=self.recv_command,args=(obj,)) # 单次消费
t3.start()
return True
except Exception as e:
print(e)
return False
if __name__=="__main__":
#订阅端示例:
from sys_config.config import config # 换成你自己的配置信息
gl = config()
gl_Redis = connect_redis(gl.REDIS_HOST,gl.REDIS_PORT,gl.REDIS_DATABASE,gl.REDIS_PWD)
r=RedisMQ(gl_Redis)
r.recv_command(None)
# chat=r.subscribe('chat') #单条订阅示例
# chat = r.psubscribe(['para_data_1:1:3','device_login_1:1:3']) #多条订阅示例
# print('开始监听')
# while True:
# print('监听中')
# # 解析数据
# msg=chat.parse_response()#block=False, timeout=60 参数解释,非阻塞模式,60秒无数据返回None
# print(msg)
# channel, data = msg[-2:]
# print('频道:',channel)
# print('数据:',data)
# # 多条订阅数据解析示例
# chat = r.continue_psubscribe([])
# while True:
# data=next(chat) #channel,
# print('频道:', channel)
# print('数据:', data)
#
# # 发布示例
# while True:
# m = input("请输入你要发布的频道:")
# n = input("请输入你要发布的消息:")
# r.publish(m, n)
# m = 'command_all'
# n= '30 31 30 33 30 31 46 34 30 30 30 38 30 34 30 32'.replace(' ','')
# n= '01 03 01 F4 00 08 04 02'.replace(' ','')
# n= '03 03 00 00 00 01 85 E8'.replace(' ','')
# n= '04 03 00 00 00 01 84 5F'.replace(' ','')
# n= '05 03 00 00 00 01 85 8E'.replace(' ','')
# n= '06 03 00 00 00 01 85 BD'.replace(' ','')
# n= '07 03 00 00 00 02 C4 6D'.replace(' ','')
# r.publish(m,n)
# m = 'command_device'
# # n = json.dumps({'device_id':"863100062008572","command":"010301F400080402"})
# n = json.dumps({'device_id':"863100061996678","command":"010301F400080402"})
# r.publish(m,n)
# print(r.publish('hello',{}))
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.
- 112.
- 113.
- 114.
- 115.
- 116.
- 117.
- 118.
- 119.
- 120.
- 121.
- 122.
- 123.
- 124.
- 125.
- 126.
- 127.
- 128.
- 129.
- 130.
- 131.
- 132.
- 133.
- 134.
- 135.
- 136.
- 137.
- 138.
- 139.
- 140.
- 141.
- 142.
- 143.
- 144.
- 145.
- 146.
- 147.
- 148.
- 149.
- 150.
- 151.
- 152.
- 153.
- 154.
- 155.
- 156.
- 157.
- 158.
- 159.
- 160.
- 161.
- 162.
- 163.
- 164.
- 165.
- 166.
- 167.
- 168.
- 169.
- 170.
- 171.
- 172.
- 173.
- 174.
- 175.
- 176.
- 177.