在Python中使用AOP实现缓存(Redis)
import redis enable=True #enable=False def readRedis(key): if enable: r = redis.Redis(host='10.224.38.31', port=8690,db=0, password='xxxx') val = r.get(key) if val is None: print "can not find data for KEY:%s \n" % (key) return None else: print "====Get VALUE from Redis by KEY:%s \n" % ( key) return pickle.loads(val) else: print "disable cache" def writeRedis(key, val): r = redis.Redis(host='10.224.38.31', port=8690,db=0, password='xxxx') if val is None: print "Val is None, don't save it to redis \n" else: r.set(key, pickle.dumps(val) ) r.expire(key, 60*60*24*7) #1week print "====Write value of KEY:%s to redis \n" % (key) import pickle, functools def cache(f): def wrapper(*args, **kwargs): key = pickle.dumps((f.__name__, args, kwargs)).replace("\n","") val = readRedis(key) if val is None: val = f(*args, **kwargs) # call the wrapped function, save in cache writeRedis(key, val) return val # read value from cache functools.update_wrapper(wrapper, f) # update wrapper's metadata return wrapper @cache def foo(n): return n*2 foo(10) # first call with parameter 10, sleeps foo(10) # returns immediately foo(15) # returns immediately foo(19) # returns immediately
相关推荐
王道革 2020-11-25
wangdonghello 2020-11-03
Langeldep 2020-11-16
chenhualong0 2020-11-16
聚合室 2020-11-16
koushr 2020-11-12
MRFENGG 2020-11-11
guoyanga 2020-11-10
fackyou00 2020-11-10
Orangesss 2020-11-03
dongCSDN 2020-10-31
rainandtear 2020-10-30
Quietboy 2020-10-30
liuyulong 2020-10-29
fansili 2020-10-29
温攀峰 2020-10-23
jackbon 2020-10-19
kaixinfelix 2020-10-04