如何恢复Heroku上Django Channels的Redis连接超限报错?
Heroku 环境下 Channels-Redis 闲置连接过期引发的连接错误自恢复指南
问题场景
- 线上服务部署在Heroku平台,多个
asyncConsumer实例通过Redis channel layer做跨实例间歇通信 - 本地开发环境无Redis连接数量限制,运行无异常;线上环境Redis存在20个连接的硬上限,超出额度就会触发服务报错
- 为规避连接超限问题,主动缩短了Redis连接的闲置过期时间,让闲置连接自动释放
- 闲置连接过期后,调用
self.channel_layer.send()指定channel名称发送消息时,会抛出aioredis层的ConnectionClosedError(报错提示为"Reader at end of file"),需要在不依赖外部调用新建asyncConsumer实例的前提下,实现错误自动恢复。
原始报错栈
ERROR Exception inside application: Reader at end of file File "/app/.heroku/python/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/app/.heroku/python/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/app/.heroku/python/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "./myapp/webhook.py", line 133, in http_request await self.channel_layer.send(userDB.backEndChannelName,{"type": "device.query"}) File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 296, in send if await connection.llen(channel_key) >= self.get_capacity(channel): File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/commands/list.py", line 70, in llen return self.execute(b'LLEN', key) File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 51, in execute return self._pool_or_conn.execute(command, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/aioredis/connection.py", line 322, in execute raise ConnectionClosedError(msg) Reader at end of file
问题根因
报错本质是Redis服务端会主动断开长时间无数据交互的闲置连接,但channels-redis底层依赖的aioredis连接池没有及时感知到这类服务端侧的连接断开,直接把已经失效的连接从池子里捞出来执行业务命令,就触发了读端EOF的连接关闭异常。之前设置的短闲置过期回收策略,本来是为了降低常驻连接数、适配Heroku的连接上限,反而提高了池内出现失效连接的概率。
自恢复实现方案(无需新建asyncConsumer实例)
- 对所有
channel_layer.send的调用逻辑增加带退避的异常捕获重试,专门拦截aioredis.exceptions.ConnectionClosedError异常 - 重试过程不需要手动重建consumer实例:aioredis的连接池本身自带失效连接自动重建能力,之前的问题是底层遇到连接断开直接把异常抛给了上层业务,只要在捕获到异常后,等待极短时间让连接池完成失效连接清理、捞取新的有效连接重试,即可完成恢复,整个过程和consumer实例状态完全解耦
- 可封装通用的带容错能力的channel发送方法,替代原生直接调用的逻辑,参考实现:
import asyncio from aioredis.exceptions import ConnectionClosedError async def robust_channel_send(channel_name, message, max_retry=2): for attempt in range(max_retry + 1): try: await self.channel_layer.send(channel_name, message) return except ConnectionClosedError: # 达到最大重试次数仍失败时直接抛出异常 if attempt == max_retry: raise # 指数退避等待,给连接池留足清理失效连接的时间 await asyncio.sleep(0.1 * (attempt + 1)) - 配合调整channels-redis的连接池参数:将
min_connections设置为远小于线上连接上限的数值(比如2-3个),配合闲置连接超时回收策略,确保连接池不会长期占满20个连接额度,从源头降低失效连接的出现概率 - 整个恢复流程完全在ChannelLayer的全局单例层面完成连接重建,不会触碰asyncConsumer的实例状态,完全满足“无需外部调用新建asyncConsumer实例”的要求
内容的提问来源于stack exchange,提问作者Hyperian
相关产品推荐
相关产品推荐

