feat(redis): add encoding for keys and optimize deletion

This commit is contained in:
InfinityPacer
2025-01-19 04:28:16 +08:00
parent cb5c06ee7e
commit 0a86b72110
+8 -4
View File
@@ -2,6 +2,7 @@ import inspect
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from functools import wraps from functools import wraps
from typing import Any, Dict, Optional from typing import Any, Dict, Optional
from urllib.parse import quote
import redis import redis
from cachetools import TTLCache from cachetools import TTLCache
@@ -213,7 +214,7 @@ class RedisBackend(CacheBackend):
""" """
# 使用 region 作为缓存键的一部分 # 使用 region 作为缓存键的一部分
region = self.get_region(region) region = self.get_region(region)
return f"region:{region}:key:{key}" return quote(f"region:{region}:key:{key}")
def set(self, key: str, value: Any, ttl: int = None, region: str = DEFAULT_CACHE_REGION, **kwargs) -> None: def set(self, key: str, value: Any, ttl: int = None, region: str = DEFAULT_CACHE_REGION, **kwargs) -> None:
""" """
@@ -270,9 +271,12 @@ class RedisBackend(CacheBackend):
""" """
try: try:
if region: if region:
pattern = f"region:{region}:key:*" redis_key = self.get_redis_key(region, "*")
for key in self.client.scan_iter(pattern): # self.client.delete(*self.client.keys(redis_key))
self.client.delete(key) with self.client.pipeline() as pipe:
for key in self.client.scan_iter(redis_key):
pipe.delete(key)
pipe.execute()
logger.info(f"Cleared Redis cache for region: {region}") logger.info(f"Cleared Redis cache for region: {region}")
else: else:
self.client.flushdb() self.client.flushdb()