4.4 KiB
4.4 KiB
Redis 配置指南
概述
本应用使用 Redis 作为 Celery 的消息代理和结果后端。在启动应用前,需要确保 Redis 服务正常运行。
Redis 安装
Windows
-
下载 Redis for Windows
# 访问 https://github.com/microsoftarchive/redis/releases # 下载最新的 .msi 文件并安装 -
使用 WSL (推荐)
# 在 WSL 中安装 sudo apt update sudo apt install redis-server sudo systemctl start redis-server sudo systemctl enable redis-server
Linux
# Ubuntu/Debian
sudo apt update
sudo apt install redis-server
sudo systemctl start redis-server
sudo systemctl enable redis-server
# CentOS/RHEL
sudo yum install redis
sudo systemctl start redis
sudo systemctl enable redis
macOS
# 使用 Homebrew
brew install redis
brew services start redis
Redis 配置
基本配置
编辑 Redis 配置文件 /etc/redis/redis.conf:
# 设置密码(可选)
requirepass your_redis_password
# 设置最大内存
maxmemory 256mb
maxmemory-policy allkeys-lru
# 持久化配置
save 900 1
save 300 10
save 60 10000
环境变量配置
在 .env 文件中配置:
# Redis 配置
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0
# 如果设置了密码
# CELERY_BROKER_URL=redis://:your_password@localhost:6379/0
# CELERY_RESULT_BACKEND=redis://:your_password@localhost:6379/0
Redis 服务管理
启动 Redis
# Windows
redis-server
# Linux (Systemd)
sudo systemctl start redis-server
# macOS (Homebrew)
brew services start redis
停止 Redis
# Linux
sudo systemctl stop redis-server
# macOS
brew services stop redis
# 手动停止
redis-cli shutdown
重启 Redis
# Linux
sudo systemctl restart redis-server
# macOS
brew services restart redis
连接测试
测试基本连接
# 使用 redis-cli
redis-cli ping
# 应该返回 PONG
# 使用项目测试脚本
python test_redis.py
检查 Redis 状态
# 查看连接信息
redis-cli info clients
# 查看内存使用
redis-cli info memory
# 查看数据库信息
redis-cli info keyspace
应用中的 Redis 集成
启动时检查
应用启动时会自动:
- 验证 Redis 连接
- 创建 Redis 客户端
- 存储到应用状态中供其他组件使用
健康检查
访问 /health 端点可以查看 Redis 连接状态:
{
"status": "healthy",
"redis": "connected"
}
故障排除
如果 Redis 连接失败,应用将无法启动。检查:
- Redis 服务是否运行
- 连接配置是否正确
- 防火墙设置
- 密码配置
生产环境建议
安全配置
-
设置密码
requirepass your_strong_password -
绑定特定 IP
bind 127.0.0.1 10.0.0.1 -
禁用危险命令
rename-command FLUSHDB "" rename-command FLUSHALL "" rename-command KEYS "" rename-command CONFIG ""
性能优化
-
设置最大内存
maxmemory 1gb maxmemory-policy allkeys-lru -
持久化配置
save 900 1 save 300 10 save 60 10000 -
连接限制
maxclients 1000
监控
-
使用 INFO 命令
redis-cli info server redis-cli info memory redis-cli info stats -
监控工具
- RedisInsight
- Redis Commander
- 自定义监控脚本
常见问题
Q: 应用启动失败,提示 Redis 连接错误
A: 检查以下几点:
- Redis 服务是否启动:
redis-cli ping - 配置文件中的 URL 是否正确
- 防火墙是否阻止连接
- Redis 密码配置是否匹配
Q: Redis 内存占用过高
A:
- 检查键的数量:
redis-cli dbsize - 设置过期策略:
CONFIG SET maxmemory-policy allkeys-lru - 清理无用键:
redis-cli FLUSHDB
Q: Celery 任务不执行
A: 检查:
- Redis 连接状态
- Celery Worker 是否启动
- 队列配置是否正确
日志位置
- 应用日志:
logs/app.log - Redis 日志:
/var/log/redis/redis.log(Linux) - Celery 日志:控制台输出或配置的日志文件
相关命令
# 查看所有键
redis-cli keys "*"
# 查看特定键
redis-cli get key_name
# 删除键
redis-cli del key_name
# 清空数据库
redis-cli flushdb
# 查看信息
redis-cli info
# 监控命令
redis-cli monitor