【发布时间】:2016-09-11 19:40:27
【问题描述】:
我正在aiohttp 中构建一个基于text/event-stream 的视图,并在aioredisimplementaion 中使用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 和keep-alive 连接将丢失。
经常丢失连接可以吗?我期待有持久的连接,如果我遗漏了什么,对不起。
【问题讨论】:
标签: python-3.x redis publish-subscribe aiohttp