网站更新内容:请访问: https://bigdata.ministep.cn/

Python订阅Redis主题,实现前端通过Websocket实时获取订阅信息【消息推送】

参考:
(23条消息) Python订阅Redis主题,实现前端通过Websocket实时获取订阅信息【消息推送】_YelloooBlue's Blog-CSDN博客]

终极解决方案
第二天起来清醒了一点,灵光一现
既然redis老是死循环,那我们能不能照葫芦画瓢,弄个异步的redis订阅?
又恶补了一下异步的知识,上网找答案
功夫不负有心人,找到个aioredis异步redis库

咋实现异步订阅嘞?这次直接在Google上搜了一下
发现了老外的一篇文章
wok,这不就是我要的吗,赶紧copy一下试试

# producer.py

import asyncio
from aioredis import create_connection, Channel
import websockets

async def subscribe_to_redis(path):
    conn = await create_connection(('localhost', 6379))

    # Set up a subscribe channel
    channel = Channel('lightlevel{}'.format(path), is_pattern=False)
    await conn.execute_pubsub('subscribe', channel)
    return channel, conn


async def browser_server(websocket, path):
    channel, conn = await subscribe_to_redis(path)
    try:
        while True:
            # Wait until data is published to this channel
            message = await channel.get()

            # Send unicode decoded data over to the websocket client
            await websocket.send(message.decode('utf-8'))

    except websockets.exceptions.ConnectionClosed:
        # Free up channel if websocket goes down
        await conn.execute_pubsub('unsubscribe', channel)
        conn.close()

if __name__ == '__main__':
    # Runs a server process on 8767. Just do 'python producer.py'
    loop = asyncio.get_event_loop()
    loop.set_debug(True)
    ws_server = websockets.serve(browser_server, 'localhost', 8767)
    loop.run_until_complete(ws_server)
    loop.run_forever()

调试了一下,完美,多客户端也有了,redis订阅也有了。

按照异步逻辑await,每有一个ws客户端连接,python都会创建一个redis订阅连接,果不其然,
在redis命令行测试的时候发现确实如此,会不会占用过多资源,还有待考究

可以说是实现了
websocket连接 转换为 redis订阅连接
也大致满足了我的项目需求了

后期需求(进阶)
redis只需要订阅一次(一个订阅链接)就可以实现对多个客户端发送,以及客户端session的判别

学习
异步IO又是一个大坑,不论是python的asyncio还是PHP的swoole,都还要学习,本文大概就到这里,记录一下研究过过程,有特别多的不足,目前项目需要跟进,有些内容暂时没法深入学习,还请见谅。

python服务器消息推送_Python Web实时消息后台服务器推送技术---GoEasy_weixin_39587407的博客-程序员宅基地 - 程序员宅基地]

posted @ 2021-11-29 19:29  ministep88  阅读(544)  评论(0编辑  收藏  举报
网站更新内容:请访问:https://bigdata.ministep.cn/