我正在构建一个text/event-stream
基于视图,aiohttp
并在aioredis
实现中使用来自 Redis 的 pub-sub。它看起来像:
从服务器获取一些数据并发布到 chanell 的脚本
def main(host, port):
server_logger.info('Got params connection host {0}, port {1}'.format(host, port))
loop = asyncio.get_event_loop()
title = None
redis = loop.run_until_complete(create_redis(('localhost', 6379)))
while True:
new_title = loop.run_until_complete(get_title(host, port))
if new_title != title:
loop.run_until_complete(redis.publish('CHANNEL', new_title))
title = new_title
loop.close()
return False
订阅频道并将其写入 Stream 响应的 aiohttp 视图
stream = web.StreamResponse()
stream.headers['Content-Type'] = 'text/event-stream'
stream.headers['Cache-Control'] = 'no-cache'
stream.headers['Connection'] = 'keep-alive'
await stream.prepare(request)
redis = await create_redis(('localhost', 6379))
channel = (await redis.subscribe('CHANNEL'))[0]
while await channel.wait_message():
message = await channel.get()
if message:
stream.write(b'event: track_update\r\n')
stream.write(b'data: ' + message + b'\r\n\r\n')
else:
continue
我得到了很多次类似的东西:
DEBUG:aioredis:Creating tcp connection to ('localhost', 6379)
所以连接丢失,这也导致concurrent.futures.CancelledError
和保持连接将丢失。经常丢失连接可以吗?我期待有持久的连接,如果我遗漏了什么,对不起。