Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -23,23 +23,21 @@ app.add_middleware(
|
|
| 23 |
|
| 24 |
# ---------------------- 关键修复:Redis连接池 + 依赖注入 ----------------------
|
| 25 |
def create_redis_pool() -> ConnectionPool:
|
| 26 |
-
"""创建Redis连接池(替代全局客户端,避免析构问题)"""
|
| 27 |
try:
|
| 28 |
pool = ConnectionPool(
|
| 29 |
-
host=os.getenv("REDIS_HOST"),
|
| 30 |
-
port=int(os.getenv("REDIS_PORT",
|
| 31 |
-
password=os.getenv("REDIS_PASSWORD"),
|
| 32 |
decode_responses=True,
|
|
|
|
| 33 |
socket_timeout=5,
|
| 34 |
-
retry_on_timeout=True
|
| 35 |
-
max_connections=10 # 限制连接数,避免资源泄漏
|
| 36 |
)
|
| 37 |
-
# 验证连接池可用性
|
| 38 |
with redis.Redis(connection_pool=pool) as client:
|
| 39 |
-
client.ping()
|
| 40 |
return pool
|
| 41 |
except Exception as e:
|
| 42 |
-
raise RuntimeError(f"Redis connection
|
| 43 |
|
| 44 |
# 初始化连接池(全局仅创建一次)
|
| 45 |
redis_pool = create_redis_pool()
|
|
|
|
| 23 |
|
| 24 |
# ---------------------- 关键修复:Redis连接池 + 依赖注入 ----------------------
|
| 25 |
def create_redis_pool() -> ConnectionPool:
|
|
|
|
| 26 |
try:
|
| 27 |
pool = ConnectionPool(
|
| 28 |
+
host=os.getenv("REDIS_HOST"), # 填 Upstash 的 Host(xxx.upstash.io)
|
| 29 |
+
port=int(os.getenv("REDIS_PORT", 6380)), # 固定填 6380(加密端口)
|
| 30 |
+
password=os.getenv("REDIS_PASSWORD"), # 填 Upstash 的实例密码
|
| 31 |
decode_responses=True,
|
| 32 |
+
ssl=True, # 必须开启 SSL,Upstash 强制加密连接
|
| 33 |
socket_timeout=5,
|
| 34 |
+
retry_on_timeout=True
|
|
|
|
| 35 |
)
|
|
|
|
| 36 |
with redis.Redis(connection_pool=pool) as client:
|
| 37 |
+
client.ping() # 验证连接
|
| 38 |
return pool
|
| 39 |
except Exception as e:
|
| 40 |
+
raise RuntimeError(f"Redis connection failed: {str(e)}")
|
| 41 |
|
| 42 |
# 初始化连接池(全局仅创建一次)
|
| 43 |
redis_pool = create_redis_pool()
|