我需要编写一个sql数据库列获取器,它接受列名和时间,并返回与输入时间相对应的该列的整列值。这可能是具有相同参数的频繁函数调用,因此我想使用 lru 缓存。但是,我不确定列名的频率是否均匀分布,因此理想情况下,我将为每个列名都有一个单独的 lru 缓存。
我以前有如下所示,但我想将每个
col_name
的 lru 分开。
@lru_cache(...)
def get_col(self, col_name, time)
# do stuff to get the column and return it
我怎样才能实现这个目标?另外,不幸的是,我必须支持 py2。
functools#lru_cache()
仅在 Python 3.x 中引入,因此您需要为每个列名称管理单独的缓存字典,这意味着:
get_col
函数中获取列数据之前,请检查列名是否在字典中。如果是,则使用关联的 LRU 缓存来获取数据。如果不是,请为该列名称创建一个新的 LRU 缓存。类似这样的
LRUCache
类:
# Assume LRUCache is a class that implements LRU cache functionality
# You would replace this with an actual LRU cache implementation
class LRUCache(object):
def __init__(self, maxsize=100):
self.cache = {}
self.maxsize = maxsize
def get(self, key):
return self.cache.get(key)
def put(self, key, value):
if len(self.cache) >= self.maxsize:
self.cache.pop(next(iter(self.cache)))
self.cache[key] = value
# Dictionary to hold separate LRU caches for each column name
column_caches = {}
def get_col(col_name, time):
# Get the LRU cache for the specified column name
# If it does not exist, create a new one
cache = column_caches.get(col_name)
if cache is None:
cache = LRUCache(maxsize=100)
column_caches[col_name] = cache
# Try to get the value from the cache
cache_key = (col_name, time)
result = cache.get(cache_key)
if result is not None:
return result
# If the value is not in the cache, fetch it
# (replace the next line with your data fetching logic)
result = "fetched data" # fetch the actual data here
# Store the fetched value in the cache and return it
cache.put(cache_key, result)
return result