1. 使用内置的`functools.lru_cache`装饰器:
```python
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) 计算斐波那契数列的第10项
2. 使用第三方库`cachetools`,它提供了多种缓存策略,如LRU、LFU和RR:
```python
from cachetools import cached, TTLCache
@cached(ttl=3600) 设置缓存时间,单位秒
def get_data_from_api():
获取数据的代码
pass
3. 使用字典实现简单的内存缓存:
```python
class Cache:
def __init__(self):
self.cache = {}
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
self.cache[key] = value
cache = Cache()
cache.set('example_key', 'example_value')
cached_value = cache.get('example_key')
print(f'从缓存中获取到的值:{cached_value}')
4. 使用`pickle`模块将对象存储到文件中实现缓存:
```python
import pickle
def get_data():
获取数据的代码
pass
def save_data_to_file(data, filename):
with open(filename, 'wb') as f:
pickle.dump(data, f)
def load_data_from_file(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
5. 使用`memcached`模块实现分布式缓存:
```python
import memcache
mc = memcache.Client(['127.0.0.1:11212'], debug=0)
mc.set('some_key', 'Some value')
value = mc.get('some_key')
mc.delete('some_key')
mc.set('key', '1')
mc.incr('key')
mc.decr('key')
6. 使用弱引用和`collections.deque`实现本地轻量级缓存:
```python
import weakref, collections
class LocalCache:
def __init__(self):
self.not_found = object()
self.cache = collections.defaultdict(list)
def get(self, key):
for k, v in self.cache.items():
if v == key:
return v
return self.not_found
def set(self, key, value, ttl=3600):
self.cache[key] = [value, time.time() + ttl]
cache = LocalCache()
cache.set('example_key', 'example_value')
cached_value = cache.get('example_key')
print(f'从缓存中获取到的值:{cached_value}')
以上方法可以根据具体需求选择使用。需要注意的是,缓存策略的选择和实现细节可能会影响缓存的效果和性能,请根据实际需求进行选择