#-*- coding: utf-8 -*-
import time
global prev_query_time
prev_query_time = None
global_data = dict(
keyword1 = 1,
keyword2 = 2,
keyword3 = 3,
)
global_cache = {}
def cache(number):
def wrap(func):
def wrap2(keyword):
global prev_query_time
if prev_query_time is None:
prev_query_time = time.time()
interval_time = time.time() - prev_query_time
if keyword in global_cache:
if interval_time>number:
prev_query_time = time.time()
result = func(keyword)
print(f"{keyword} time out get from db {result}")
global_cache[keyword] = result
return result
else:
result = global_cache.get(keyword)
print(f"{keyword} get from cache {result}")
return result
else:
prev_query_time = time.time()
result = func(keyword)
global_cache[keyword] = result
print(f"{keyword} not in cache get from db {result}")
return result
return wrap2
return wrap
def get_data_from_db(keyword):
#can query from redis,mysql
result = global_data.get(keyword)
return result
def get_data_from_cache(keyword):
result = global_data.get(keyword)
return result
@cache(5)
def query(keyword):
result = get_data_from_db(keyword)
return result
if __name__ == "__main__":
query("keyword1")
query("keyword1")
query("keyword2")
time.sleep(6)
query("keyword1")
类实现
#-*- coding: utf-8 -*-
import time
global_cache = {}
class Cache(object):
def __init__(self,number):
self.number = number
self.prev_query_time = None
def __call__(self,func):
def wrap2(keyword):
if self.prev_query_time is None:
self.prev_query_time = time.time()
interval_time = time.time() - self.prev_query_time
if keyword in global_cache:
if interval_time>self.number:
self.prev_query_time = time.time()
result = func(keyword)
print(f"{keyword} time out get from db {result}")
global_cache[keyword] = result
return result
else:
result = global_cache.get(keyword)
print(f"{keyword} get from cache {result}")
return result
else:
self.prev_query_time = time.time()
result = func(keyword)
global_cache[keyword] = result
print(f"{keyword} not in cache get from db {result}")
return result
return wrap2
def get_data_from_cache(keyword):
result = global_data.get(keyword)
return result
def get_data_from_db(keyword):
global_data = dict(
keyword1 = 1,
keyword2 = 2,
keyword3 = 3,
)
result = global_data.get(keyword)
return result
@Cache(5)
def query(keyword):
result = get_data_from_db(keyword)
return result
if __name__ == "__main__":
query("keyword1")
query("keyword1")
query("keyword2")
time.sleep(6)
query("keyword1")