在Python中使用AOP實(shí)現(xiàn)Redis緩存示例
更新時間:2017年07月11日 09:44:12 作者:flyfoxs
本篇文章主要介紹了在Python中使用AOP實(shí)現(xiàn)Redis緩存示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
越來越覺得的緩存是計算機(jī)科學(xué)里最NB的發(fā)明(沒有之一),本文就來介紹了一下在Python中使用AOP實(shí)現(xiàn)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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python 實(shí)現(xiàn)圖像逐像素點(diǎn)取鄰域數(shù)據(jù)
這篇文章主要介紹了Python 實(shí)現(xiàn)圖像逐像素點(diǎn)取鄰域數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python運(yùn)用于數(shù)據(jù)分析的簡單教程
這篇文章主要介紹了Python運(yùn)用于數(shù)據(jù)分析的簡單教程,主要介紹了如何運(yùn)用Python來進(jìn)行數(shù)據(jù)導(dǎo)入、變化、統(tǒng)計和假設(shè)檢驗(yàn)等基本的數(shù)據(jù)分析,需要的朋友可以參考下2015-03-03終端能到import模塊 解決jupyter notebook無法導(dǎo)入的問題
這篇文章主要介紹了在終端能到import模塊 而在jupyter notebook無法導(dǎo)入的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03