|
6 | 6 | import redis.asyncio as redis |
7 | 7 |
|
8 | 8 | from log import logger |
| 9 | +from schemas.base import Fail, Success, SuccessExtra |
9 | 10 | from settings.config import settings |
10 | 11 |
|
11 | 12 |
|
@@ -149,14 +150,35 @@ async def wrapper(*args, **kwargs): |
149 | 150 | cached_result = await cache_manager.get(cache_key) |
150 | 151 | if cached_result is not None: |
151 | 152 | logger.debug(f"缓存命中: {cache_key}") |
| 153 | + if isinstance(cached_result, dict) and cached_result.get("__response__"): |
| 154 | + response_type = cached_result.get("class") |
| 155 | + payload = cached_result.get("payload", {}) |
| 156 | + response_cls = { |
| 157 | + "Success": Success, |
| 158 | + "Fail": Fail, |
| 159 | + "SuccessExtra": SuccessExtra, |
| 160 | + }.get(response_type, Success) |
| 161 | + return response_cls(**payload) |
152 | 162 | return cached_result |
153 | 163 |
|
154 | 164 | # 执行原函数 |
155 | 165 | result = await func(*args, **kwargs) |
156 | 166 |
|
157 | 167 | # 设置缓存 |
158 | 168 | if result is not None: |
159 | | - await cache_manager.set(cache_key, result, ttl) |
| 169 | + value_to_cache: Any = result |
| 170 | + if isinstance(result, (Success, Fail, SuccessExtra)): |
| 171 | + body_bytes = result.body |
| 172 | + if isinstance(body_bytes, bytes): |
| 173 | + payload = json.loads(body_bytes.decode("utf-8")) |
| 174 | + else: |
| 175 | + payload = json.loads(body_bytes) |
| 176 | + value_to_cache = { |
| 177 | + "__response__": True, |
| 178 | + "class": result.__class__.__name__, |
| 179 | + "payload": payload, |
| 180 | + } |
| 181 | + await cache_manager.set(cache_key, value_to_cache, ttl) |
160 | 182 | logger.debug(f"缓存设置: {cache_key}") |
161 | 183 |
|
162 | 184 | return result |
|
0 commit comments