feat: cache impl done

This commit is contained in:
Relakkes
2024-06-02 19:57:13 +08:00
parent 6c4116f240
commit 4bba1447f8
16 changed files with 180 additions and 43 deletions

5
cache/__init__.py vendored
View File

@@ -1,5 +0,0 @@
# -*- coding: utf-8 -*-
# @Author : relakkes@gmail.com
# @Name : 程序员阿江-Relakkes
# @Time : 2024/6/2 11:05
# @Desc :

13
cache/abs_cache.py vendored
View File

@@ -5,10 +5,10 @@
# @Desc : 抽象类
from abc import ABC, abstractmethod
from typing import Any, Optional
from typing import Any, List, Optional
class Cache(ABC):
class AbstractCache(ABC):
@abstractmethod
def get(self, key: str) -> Optional[Any]:
@@ -31,3 +31,12 @@ class Cache(ABC):
:return:
"""
raise NotImplementedError
@abstractmethod
def keys(self, pattern: str) -> List[str]:
"""
获取所有符合pattern的key
:param pattern: 匹配模式
:return:
"""
raise NotImplementedError

29
cache/cache_factory.py vendored Normal file
View File

@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# @Author : relakkes@gmail.com
# @Name : 程序员阿江-Relakkes
# @Time : 2024/6/2 11:23
# @Desc :
class CacheFactory:
"""
缓存工厂类
"""
@staticmethod
def create_cache(cache_type: str, *args, **kwargs):
"""
创建缓存对象
:param cache_type: 缓存类型
:param args: 参数
:param kwargs: 关键字参数
:return:
"""
if cache_type == 'memory':
from .local_cache import ExpiringLocalCache
return ExpiringLocalCache(*args, **kwargs)
elif cache_type == 'redis':
from .redis_cache import RedisCache
return RedisCache()
else:
raise ValueError(f'Unknown cache type: {cache_type}')

25
cache/local_cache.py vendored
View File

@@ -6,12 +6,12 @@
import asyncio
import time
from typing import Any, Dict, Optional, Tuple
from typing import Any, Dict, List, Optional, Tuple
from abs_cache import Cache
from cache.abs_cache import AbstractCache
class ExpiringLocalCache(Cache):
class ExpiringLocalCache(AbstractCache):
def __init__(self, cron_interval: int = 10):
"""
@@ -60,6 +60,21 @@ class ExpiringLocalCache(Cache):
"""
self._cache_container[key] = (value, time.time() + expire_time)
def keys(self, pattern: str) -> List[str]:
"""
获取所有符合pattern的key
:param pattern: 匹配模式
:return:
"""
if pattern == '*':
return list(self._cache_container.keys())
# 本地缓存通配符暂时将*替换为空
if '*' in pattern:
pattern = pattern.replace('*', '')
return [key for key in self._cache_container.keys() if pattern in key]
def _schedule_clear(self):
"""
开启定时清理任务,
@@ -93,13 +108,13 @@ class ExpiringLocalCache(Cache):
await asyncio.sleep(self._cron_interval)
if __name__ == '__main__':
cache = ExpiringLocalCache(cron_interval=2)
cache.set('name', '程序员阿江-Relakkes', 3)
print(cache.get('key'))
print(cache.keys("*"))
time.sleep(4)
print(cache.get('key'))
del cache
time.sleep(1)
print("done")
print("done")

15
cache/redis_cache.py vendored
View File

@@ -3,18 +3,18 @@
# @Name : 程序员阿江-Relakkes
# @Time : 2024/5/29 22:57
# @Desc : RedisCache实现
import os
import pickle
import time
from typing import Any
from typing import Any, List
from abs_cache import Cache
from redis import Redis
from cache.abs_cache import AbstractCache
from config import db_config
class RedisCache(Cache):
class RedisCache(AbstractCache):
def __init__(self) -> None:
# 连接redis, 返回redis客户端
self._redis_client = self._connet_redis()
@@ -53,12 +53,19 @@ class RedisCache(Cache):
"""
self._redis_client.set(key, pickle.dumps(value), ex=expire_time)
def keys(self, pattern: str) -> List[str]:
"""
获取所有符合pattern的key
"""
return [key.decode() for key in self._redis_client.keys(pattern)]
if __name__ == '__main__':
redis_cache = RedisCache()
# basic usage
redis_cache.set("name", "程序员阿江-Relakkes", 1)
print(redis_cache.get("name")) # Relakkes
print(redis_cache.keys("*")) # ['name']
time.sleep(2)
print(redis_cache.get("name")) # None