flask_redis 如何自动重连 
时间: 2023-05-14 15:05:57 浏览: 41
Flask-Redis 提供了一个名为 RedisRetry 的类,可以用来自动重连。你可以在 Flask 应用程序中使用以下代码:
```
from flask_redis import FlaskRedis
from redis.exceptions import ConnectionError
redis_store = FlaskRedis()
def create_app():
app = Flask(__name__)
app.config['REDIS_URL'] = 'redis://localhost:6379/0'
redis_store.init_app(app)
@app.before_request
def before_request():
try:
redis_store.ping()
except ConnectionError:
redis_store.redis.connection_pool.disconnect()
redis_store.redis.connection_pool.reset()
redis_store.redis.connection_pool.connection_kwargs['password'] = 'your_password'
redis_store.redis.connection_pool.connection_kwargs['host'] = 'your_host'
redis_store.redis.connection_pool.connection_kwargs['port'] = 'your_port'
redis_store.redis.connection_pool.connection_kwargs['db'] = 'your_db'
redis_store.redis.connection_pool.connection_kwargs['socket_timeout'] = None
return app
```
这段代码会在每个请求之前检查 Redis 连接是否正常,如果连接失败,就会自动重连。如果你需要更改 Redis 的连接参数,可以在 before_request 函数中修改 connection_kwargs。
相关推荐

















