您的位置:首页 > 数据库 > Redis

django使用redis做缓存(非django-redis模块)

2019-02-24 11:34 260 查看

昨天面试去面试官问redis的主要作用是什么
我回答:是做队列进行统一资源调度
结果面试官看了我一眼说:redis主要是用来做缓存的
当时别提多尴尬
回来以后再django下写了一个简单的redis缓存代码

#查看redis 中是否有a开头的数据, 如果没有则去mysql中取  取到以后再放到缓存中
pool = redis.ConnectionPool(host="127.0.0.1", port=6379)
r = redis.Redis(connection_pool=pool)
News=[]
res=r.keys('a*')
for z in res:
#print(r.hgetall(z))
temp=r.hgetall(z)
#print(r.hget(z, b'goodsname'))  # 输出:bb
if temp:
#h1 = str(temp, encoding='utf-8')
News+=temp
if News:
return render(request, 'myhome/index.html', {'navdata': data, 'news': News})
else:
News=Goods.objects.filter(cateid_id=tab)
News_cache={}
#存入redis, 如果必要写入有效时间
for i in News:
#print(i.id)
News_cache={'id':str(i.id),'pic_url':str(i.pic_url),'goodsname':str(i.goodsname),'addtime':str(i.addtime)}
#print(type(News_cache))
r.hmset('a'+str(i.id), News_cache)

return render(request,'myhome/index.html',{'navdata':data,'news':News})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: