字典的方式缓存
1、直接class对象中定义字典,然后将数据以键值对的方式保存及后期调用。
class Test(object):
def __init__(self):
self.dict_cache = {}
def get_num(key):
if key in self.dict_cache:
return self.dict_cache[key]
else:
value = key + '_'
# 保存没有的结果值
self.dict_cache[key] = value
2、使用 lru_cache装饰器保存函数结果
from functools import lru_cache
@lru_cache(maxsize=32)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
fibonacci(30)
装饰器会保存函数中间返回结果值,其中maxsize表示最多能保存的调用次数,超过时,会使用先进先出的方式保持缓存的大小。
3、使用LRUCach创建一定大小的缓存条,并保持先进先出的原则。
from cachetools import LRUCache, TTLCache
class Caculate(object):
def __init__(self):
self.test_dict = {'1':1,'2':2,'3':3,'4':4}
self.cache_need = LRUCache(maxsize=3) ## 定义一个缓存需要的
self.cache_un_need = LRUCache(maxsize=3) ## 定义一个缓存不需要的
def main_function(self,num):
atest = []
if str(num) in self.test_dict:
a = str(num) + '有'
atest.append(a)
elif str(num) in self.cache_un_need:
a = str(num) + '需要的候补'
atest.append(a)
elif str(num) in self.cache_need:
a = str(num) + '不需要的候补'
atest.append(a)
elif num <= 10:
self.cache_need[str(num)] = num
a = str(num)+'小无'
atest.append(a)
else:
self.cache_un_need[str(num)] = num
a = str(num)+'大无'
atest.append(a)
return atest
Caculate = Caculate()
atest = [4,5,6,7,8,6,9,10,11,12,13,14,15,16,17,16,8,7,15,14]
for i in atest:
print(i, Caculate.main_function(i))
print(Caculate.cache_need)
print(Caculate.cache_un_need)
其中输出结果是:
4 ['4有']
5 ['5小无']
6 ['6小无']
7 ['7不需要的候补']
8 ['8小无']
6 ['6不需要的候补']
9 ['9小无']
10 ['10小无']
11 ['11大无']
12 ['12大无']
13 ['13大无']
14 ['14大无']
15 ['15大无']
16 ['16大无']
17 ['17大无']
16 ['16需要的候补']
8 ['8不需要的候补']
7 ['7小无']
15 ['15需要的候补']
14 ['14大无']
LRUCache([('9', 9), ('10', 10), ('7', 7)], maxsize=3, currsize=3)
LRUCache([('16', 16), ('17', 17), ('14', 14)], maxsize=3, currsize=3)
5、使用redis作为缓存
import redis
# 链接数据库
r = redis.Redis(host='localhost', port=6379)
# 将数据存到redis里(这里设置了存储数据的过期时间是60秒)
r.set('foo', 'bar') # 将字符圈bar存到redis里,并关联到键foo上
r.expire('foo', 60)
# 设置键值对,过期时间为10秒
r.set('key', 'value', ex=10)
# 获取键值对
value = r.get('foo')
print(value)