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

昨天面试去面试官问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})

猜你喜欢

转载自blog.csdn.net/weixin_44222183/article/details/87901385