本文目录导读:

我来分享几种提升Python缓存查询响应速度的方法:
使用高效的数据结构
字典/Hash表
# 使用字典作为简单缓存
class SimpleCache:
def __init__(self):
self.cache = {}
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
self.cache[key] = value
# O(1)查询速度
cache = SimpleCache()
cache.set("user_123", {"name": "Alice"})
result = cache.get("user_123")
使用functools.lru_cache
from functools import lru_cache
@lru_cache(maxsize=1000)
def expensive_function(n):
# 模拟耗时操作
return n * n
# 自动缓存函数结果
result = expensive_function(42) # 计算
result = expensive_function(42) # 直接从缓存读取
使用Redis等内存数据库
安装redis
pip install redis
高性能缓存实现
import redis
import json
import hashlib
class RedisCache:
def __init__(self, host='localhost', port=6379, db=0):
self.client = redis.Redis(
host=host,
port=port,
db=db,
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2
)
def get_or_compute(self, key, compute_func, ttl=300):
"""先查缓存,没有则计算并缓存"""
# 尝试从缓存获取
cached = self.client.get(key)
if cached is not None:
return json.loads(cached)
# 计算新值
value = compute_func()
# 存入缓存,设置过期时间
self.client.setex(key, ttl, json.dumps(value))
return value
cache = RedisCache()
def get_user_data(user_id):
return cache.get_or_compute(
f"user:{user_id}",
lambda: fetch_from_database(user_id),
ttl=3600 # 1小时过期
)
使用本地缓存库
cachetools库
from cachetools import TTLCache, LRUCache
from cachetools import cached
# TTL缓存 - 自动过期
ttl_cache = TTLCache(maxsize=100, ttl=300) # 5分钟过期
@cached(ttl_cache)
def get_expensive_data(param):
return expensive_database_query(param)
# LRU缓存 - 最近最少使用
lru_cache = LRUCache(maxsize=1000)
@cached(lru_cache)
def get_frequently_used_data(param):
return expensive_computation(param)
多级缓存策略
class MultiLevelCache:
def __init__(self):
self.l1_cache = {} # 内存缓存
self.l2_cache = redis.Redis() # Redis缓存
self.ttl_l1 = 60 # L1缓存60秒
self.ttl_l2 = 3600 # L2缓存1小时
def get(self, key, compute_func):
# 1. 查L1缓存
if key in self.l1_cache:
value, timestamp = self.l1_cache[key]
if time.time() - timestamp < self.ttl_l1:
return value
else:
del self.l1_cache[key]
# 2. 查L2缓存
cached = self.l2_cache.get(key)
if cached is not None:
self.l1_cache[key] = (json.loads(cached), time.time())
return cached
# 3. 计算并缓存
value = compute_func()
self.l2_cache.setex(key, self.ttl_l2, json.dumps(value))
self.l1_cache[key] = (value, time.time())
return value
预加载和延迟加载
import threading
import time
class PreloadCache:
def __init__(self, load_func, refresh_interval=60):
self.load_func = load_func
self.refresh_interval = refresh_interval
self.cache = None
self.lock = threading.Lock()
# 启动预加载线程
threading.Thread(target=self._refresh_loop, daemon=True).start()
def _refresh_loop(self):
"""后台定时刷新缓存"""
while True:
try:
new_data = self.load_func()
with self.lock:
self.cache = new_data
except Exception as e:
print(f"Cache refresh failed: {e}")
time.sleep(self.refresh_interval)
def get(self):
"""获取缓存数据,若None则同步加载"""
if self.cache is None:
self.cache = self.load_func()
return self.cache
# 使用示例
cache = PreloadCache(lambda: expensive_data_load(), refresh_interval=300)
异步缓存加速
import asyncio
import aioredis
class AsyncCache:
def __init__(self):
self.redis = None
async def initialize(self):
self.redis = await aioredis.create_redis_pool(
'redis://localhost',
minsize=5,
maxsize=10
)
async def get_or_compute(self, key, compute_coroutine, ttl=300):
# 异步获取缓存
cached = await self.redis.get(key)
if cached:
return json.loads(cached)
# 异步计算
value = await compute_coroutine()
# 异步缓存
await self.redis.setex(key, ttl, json.dumps(value))
return value
性能优化技巧
本地缓存 vs 远程缓存
# 对于高频率访问的小数据,使用本地缓存
local_cache = {}
# 对于低频大数据,使用Redis
remote_cache = RedisCache()
def smart_get(key, compute_func):
# 判断数据大小决定缓存策略
if len(key) < 100: # 小数据
return local_cache.get(key, compute_func)
else: # 大数据
return remote_cache.get(key, compute_func)
使用pickle序列化
import pickle
# pickle比json更快(对于复杂对象)
def serialize(value):
return pickle.dumps(value)
def deserialize(data):
return pickle.loads(data)
性能对比建议
| 缓存方案 | 速度 | 适用场景 |
|---|---|---|
| 本地字典 | 极快 | 小数据、单进程 |
| LRU Cache | 快 | 频繁访问的热点数据 |
| Redis | 中 | 分布式、大数据量 |
| 内存缓存库 | 快 | 需要TTL功能 |
实际应用示例
class OptimizedCache:
def __init__(self):
# 热数据:本地缓存
self.hot_cache = TTLCache(maxsize=1000, ttl=60)
# 温数据:Redis
self.warm_cache = RedisCache()
# 冷数据:数据库查询(不缓存)
def get_data(self, key, compute_func, priority='normal'):
if priority == 'hot':
# 高优先级:优先本地缓存
return self.hot_cache.get(key) or self._fetch_and_cache(key, compute_func)
else:
# 普通优先级:直接查数据库或Redis
return self.warm_cache.get_or_compute(key, compute_func)
通过这些方法,可以显著提升Python应用的缓存查询响应速度,选择哪种方案取决于你的具体场景、数据量和性能要求。