前后端分离:后端如何刷新 Next.js 缓存?(续)
# services/cache.py
import httpx
from config import settings
async def revalidate_nextjs_cache(tags: list[str]):
"""通知 Next.js 刷新指定标签的缓存"""
async with httpx.AsyncClient() as client:
try:
response = await client.post(
f"{settings.NEXTJS_URL}/api/revalidate",
json={"tags": tags},
headers={
"Authorization": f"Bearer {settings.REVALIDATION_SECRET}"
},
timeout=5.0,
)
response.raise_for_status()
return response.json()
except httpx.HTTPError as e:
# 缓存刷新失败不应该阻塞业务逻辑
# 记录日志,但不抛异常
print(f"Cache revalidation failed: {e}")
return None