在Python中使用AOP实现Redis缓存示例
作者:flyfoxs 时间:2021-09-12 11:18:45
越来越觉得的缓存是计算机科学里最NB的发明(没有之一),本文就来介绍了一下在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
来源:http://flyfoxs.iteye.com/blog/2383929?utm_source=tuicool&utm_medium=referral
标签:Python,Redis缓存
0
投稿
猜你喜欢
Go语言反射reflect.Value实现方法的调用
2023-07-22 15:50:11
asp防止同时登陆的问题
2007-10-26 12:19:00
golang image图片处理示例
2024-05-22 17:44:02
js 模拟实现类似c#下的hashtable的简单功能代码
2024-04-19 09:44:51
Django框架使用内置方法实现登录功能详解
2021-11-01 00:54:50
浅谈keras中的batch_dot,dot方法和TensorFlow的matmul
2023-04-08 07:21:28
python中sqllite插入numpy数组到数据库的实现方法
2024-01-16 20:31:29
web2.0中流行的设计元素:颜色
2007-12-10 12:16:00
基于python爬取链家二手房信息代码示例
2022-09-01 18:36:25
Python 编程速成(推荐)
2021-04-03 04:30:10
网站导航设计的6大分类
2010-07-12 18:46:00
python异常的传递知识点总结
2023-07-12 19:19:58
通过字符串导入 Python 模块的方法详解
2023-10-15 03:00:56
python实现b站直播自动发送弹幕功能
2023-07-13 06:58:15
在IE浏览器下面指定表单编码方式
2009-10-02 16:47:00
golang之JWT实现的示例代码
2024-01-30 03:35:30
mysql 替换字段部分内容及mysql 替换函数replace()
2024-01-23 19:25:27
基于 Serverless +企业微信打造 nCoV 疫情监控小助手
2023-11-20 21:42:02
Python教程之基本运算符的使用(下)
2021-04-29 20:32:37
Python类的基础入门知识
2021-07-09 04:07:25