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

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")