【消息中间件】基于Redis的消息中间件封装组件

基于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',{}))
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神精兵院院长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值