48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
"""磁盘缓存工具:diskcache 增删查的统一封装。
|
|
|
|
真实工程里,撮合链路的状态(如订单号、行情快照、断言上下文)
|
|
需要在多个脚本/进程间同步:压测脚本写入,校验脚本读取。直接连
|
|
DB 会把验证逻辑和业务库耦合,故用 diskcache 做一层本地磁盘缓存,
|
|
API 收敛为 set/get/delete 三个动词,缓存目录可注入。
|
|
|
|
演示工程统一使用脱敏路径 ``/tmp/demo/cache``。
|
|
"""
|
|
|
|
import diskcache
|
|
|
|
#: 演示用缓存目录(脱敏占位,非真实生产路径)
|
|
DEFAULT_CACHE_PATH = "/tmp/demo/cache"
|
|
|
|
|
|
def set(key: str, value, path: str = DEFAULT_CACHE_PATH) -> None:
|
|
"""写入缓存。
|
|
|
|
:param key: 缓存键
|
|
:param value: 缓存值(须可被 pickle 序列化)
|
|
:param path: 缓存目录
|
|
"""
|
|
with diskcache.Cache(path) as cache:
|
|
cache.set(key, value)
|
|
|
|
|
|
def get(key: str, path: str = DEFAULT_CACHE_PATH):
|
|
"""读取缓存,键不存在返回 None。
|
|
|
|
:param key: 缓存键
|
|
:param path: 缓存目录
|
|
:return: 缓存值或 None
|
|
"""
|
|
with diskcache.Cache(path) as cache:
|
|
return cache.get(key)
|
|
|
|
|
|
def delete(key: str, path: str = DEFAULT_CACHE_PATH) -> bool:
|
|
"""删除缓存。
|
|
|
|
:param key: 缓存键
|
|
:param path: 缓存目录
|
|
:return: 是否实际删除(键不存在时为 False)
|
|
"""
|
|
with diskcache.Cache(path) as cache:
|
|
return cache.delete(key)
|