https://blog.csdn.net/ybn6775/article/details/80865425
FIFO缓存策略:
首先缓存两个基本的特点, 一个是缓存空间有限, 另一个是数据过期,缓存空间有限就需要我们对有限的控件进行利用,数据的置换策略非常重要,基本的置换策略有FIFO、LRU、LFU,其中FIFO最为简单,其基本假设就是最近被加载进来的数据下次使用到的可能性大于之前被加载进来的数据,对于符合这种假设的场景较为适用。其python代码如下:
class FIFOCache(object):
"""
数据缓存类, 当前使用FIFO策略, 设置过期时间戳
"""
def __init__(self, cache_time, opacity):
"""
数据缓存类初始化
"""
# 数据缓存的时间长短, 秒为单位
self.cache_time = cache_time
# 数据池的大小
self.opacity = opacity
# 当前数据的索引
self._index = 0
# 缓存的字典key的列表
self._key_list = [None for i in xrange(self.opacity)]
# 缓存数据的查询字典
self._data_cache = {}
def push_data(self, key, data):
"""
将数据缓存
"""
if not isinstance(data, dict):
return
# 数据进来的时候的时间戳
data['_time_stamps'] = int(time.time())
# 如果key已经在字典中, 直接更新, 保持list中key不同
if key in self._data_cache:
self._data_cache[key] = data
return
# 索引循环
if self._index >= self.opacity:
self._index = 0
# 删除老的数据
old_key = self._key_list[self._index]
self._data_cache.pop(old_key, 0)
# 加入新的数据
self._data_cache[key] = data
# 索引递增
self._key_list[self._index] = key
self._index += 1
def get_data(self, key):
"""
取出缓存的数据
"""
# 检查下出来时候时间戳
data = self._data_cache.get(key, {})
time_stamp = data.get('_time_stamps', 0)
if time.time() - time_stamp < self.cache_time:
return data
else:
return None
def destory(self):
"""
缓存的销毁
"""
self._data_cache.clear()
self._key_list = []