在 aiohttp 应用程序中与 Redis(aioredis) 失去连接

Loosing connection with Redis(aioredis) inside aiohttp app

我正在 aiohttp 中构建一个基于 text/event-stream 的视图,并且还在 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

订阅频道并将其写入流响应的 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 并且保持活动连接将丢失。 经常断开连接可以吗?我期待有持久的联系,抱歉,如果我遗漏了什么。

起初在请求处理程序中创建新的 redis 连接是个坏主意。 请为每个应用程序使用一个连接池。

您可能会 https://github.com/KeepSafe/aiohttp/blob/master/demos/polls/aiohttpdemo_polls/main.py 作为推荐设计原则的草图。

关于保持连接——它们不是很持久,但默认情况下会在 75 秒不活动期后关闭。

您可以通过将 keep_alive=300 参数传递给 app.make_handler() 调用来增加周期,但设置非常大的值并不稳健——在 TCP 自然连接期间,在某些情况下可能会在没有通知的情况下中断。 如果您没有要传递的数据,最好保持合理的慢超时并定期向服务器发送自定义 ping 请求。