redis自定义缓存

Posted zhedadao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis自定义缓存相关的知识,希望对你有一定的参考价值。

技术分享图片
 1 import weakref, collections
 2 import time
 3 
 4 
 5 class LocalCache():
 6     notFound = object()
 7 
 8     class Dict(dict):
 9         def __del__(self):
10             pass
11 
12     def __init__(self,maxlen=20):
13         self.weak = weakref.WeakKeyDictionary()
14         self.strong=collections.deque(maxlen=maxlen)
15 
16     @staticmethod
17     def nowTime():
18         return int(time.time())
19 
20     def get(self, key):
21         # 每个键值对后面加个字段过期时间
22         # 第一次获取 expire=当前时间+过期时间
23         # 非第一次获取时候,expire判断是否过期,过期可认为数据没有找到
24         # 过期后应该删除数据
25         value = self.weak.get(key, self.notFound)
26         # 没有过期
27         if (value is not self.notFound):
28             expire = value[rexpire]
29             # 已经过期
30             if (self.nowTime() > expire):
31                 return self.notFound
32             else:
33                 return value
34         # 过期了-返回没有找到
35         else:
36             return self.notFound
37     def set(self,key,value):
38         self.weak[key]=strongRef=LocalCache.Dict(value)
39         self.strong.append(strongRef)
40 
41 
42 from functools import wraps
43 
44 
45 def funcCache(expire=1):
46     caches = LocalCache()
47 
48     def _wrappend(func):
49         @wraps(func)
50         def __wrapped(*args, **kwargs):
51             # 计算出缓存的key值
52             key = str(func) + str(args) + str(kwargs)
53 
54             result = caches.get(key)
55 
56             if (result is LocalCache.notFound):
57                 result = func(*args, **kwargs)
58 
59                 caches.set(key, {rresult: result, rexpire: expire + caches.nowTime()})
60 
61                 result = caches.get(key)
62 
63             return result
64 
65         return __wrapped
66 
67     return _wrappend
68 f=funcCache()
View Code

 

以上是关于redis自定义缓存的主要内容,如果未能解决你的问题,请参考以下文章

redis自定义缓存

Spring Boot自定义Redis缓存配置,保存value格式JSON字符串

spring缓存自定义resolver

spring缓存自定义resolver

spring缓存自定义resolver

SpringBoot2.x整合Redis缓存自定义序列化