脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 在Python中使用AOP实现Redis缓存示例

在Python中使用AOP实现Redis缓存示例

2020-11-25 00:16flyfoxs Python

本篇文章主要介绍了在Python中使用AOP实现Redis缓存示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

越来越觉得的缓存是计算机科学里最NB的发明(没有之一),本文就来介绍了一下在Python中使用AOP实现Redis缓存示例,小伙伴们一起来了解一下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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

延伸 · 阅读

精彩推荐