This commit is contained in:
2026-08-18 16:13:07 +08:00
parent efcbc49096
commit 4de893ca94
12 changed files with 906 additions and 506 deletions
+49 -22
View File
@@ -1,18 +1,50 @@
import inspect
import json
import logging
from api.core.Gzip import gzip_zip, gzip_unzip
from config.main import config
logger = logging.getLogger('dcalc.redis_cache')
async def get_redis_info_async(redis, key, fun, expire = 0, without_gzip=False):
def _read_cached(redis, key, without_gzip):
content = redis.get(key)
if content is None:
return None
return json.loads(content if without_gzip else gzip_unzip(content))
def _write_cached(redis, key, info, expire, without_gzip):
content = json.dumps(info) if without_gzip else gzip_zip(json.dumps(info))
if expire > 0:
redis.set(key, content, ex=expire)
else:
redis.set(key, content)
async def _read_cached_async(redis, key, without_gzip):
content = await redis.get(key)
if content is None:
return None
return json.loads(content if without_gzip else gzip_unzip(content))
async def _write_cached_async(redis, key, info, expire, without_gzip):
content = json.dumps(info) if without_gzip else gzip_zip(json.dumps(info))
if expire > 0:
await redis.set(key, content, ex=expire)
else:
await redis.set(key, content)
async def get_redis_info_async(redis, key, fun, expire=0, without_gzip=False):
info = None
if not config.DEBUG_MODE and redis:
try:
if without_gzip:
info = json.loads(redis.get(key))
else:
info = json.loads(gzip_unzip(redis.get(key)))
info = await _read_cached_async(redis, key, without_gzip)
except Exception:
logger.warning('read Redis cache failed key=%s', key, exc_info=True)
info = None
if info is None:
if inspect.iscoroutinefunction(fun):
@@ -20,31 +52,26 @@ async def get_redis_info_async(redis, key, fun, expire = 0, without_gzip=False):
else:
info = fun()
if not config.DEBUG_MODE and redis and info is not None:
if without_gzip:
redis.set(key, json.dumps(info))
else:
redis.set(key, gzip_zip(json.dumps(info)))
if expire > 0:
redis.expire(key, expire)
try:
await _write_cached_async(redis, key, info, expire, without_gzip)
except Exception:
logger.warning('write Redis cache failed key=%s', key, exc_info=True)
return info
def get_redis_info(redis, key, fun, expire = 0, without_gzip=False):
def get_redis_info(redis, key, fun, expire=0, without_gzip=False):
info = None
if not config.DEBUG_MODE and redis:
try:
if without_gzip:
info = json.loads(redis.get(key))
else:
info = json.loads(gzip_unzip(redis.get(key)))
info = _read_cached(redis, key, without_gzip)
except Exception:
logger.warning('read Redis cache failed key=%s', key, exc_info=True)
info = None
if info is None:
info = fun()
if not config.DEBUG_MODE and redis and info is not None:
if without_gzip:
redis.set(key, json.dumps(info))
else:
redis.set(key, gzip_zip(json.dumps(info)))
if expire > 0:
redis.expire(key, expire)
try:
_write_cached(redis, key, info, expire, without_gzip)
except Exception:
logger.warning('write Redis cache failed key=%s', key, exc_info=True)
return info