一.配置文件settings.py中
# 設置django緩存存放位置為redis數據庫,並設置一個默認(default)選項,在redis中(配置文件/etc/redis/redis.conf)開啟了RDB持久化儲存 # pip install django-redis, 然后在視圖中可以通過 from django_redis import get_redis_connection 這個方法和redis數據庫進行連接 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", # redis服務器的ip地址及端口號,及數據庫序號,redis一共有15個數據庫 0~15 "LOCATION": "redis://127.0.0.1:6379/6",
# "LOCATION": "redis://:passwordpassword@47.193.146.xxx:6379/0", # 如果redis設置密碼的話,需要以這種格式進行設置,host前面是密碼 "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }
二.某個應用的視圖文件views.py中
from django.shortcuts import render, redirect from django.views.generic import View from goods.models import GoodsType, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner, GoodsSKU from order.models import OrderGoods from django_redis import get_redis_connection # 使用該模塊的方法, 可以設置和取出緩存(緩存一些無須用戶登錄就可以獲取的數據) # 保存緩存的載體已經在settings中設置成redis from django.core.cache import cache from django.core.urlresolvers import reverse from django.core.paginator import Paginator # http://127.0.0.1:8000/index class IndexView(View): """首頁""" def get(self, request): """顯示網頁""" # 每次來自瀏覽器首頁的請求,都先嘗試獲取緩存 context = cache.get('index_page_data')
# 刪除緩存
# cache.delete("鍵名")
if context is None: # 獲取商品分類信息, 有那幾大類商品 types = GoodsType.objects.all() # 獲取首頁輪播商品的信息 index_banner = IndexGoodsBanner.objects.all().order_by('index') # 獲取首頁促銷活動的信息 promotion_banner = IndexPromotionBanner.objects.all().order_by('index') # 獲取首頁分類商品活動的信息 # types_goods_banner = IndexTypeGoodsBanner.objects.all() for type in types: # 根據type查詢type種類首頁展示的文字商品信息和圖片商品信息 title_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index') image_banner = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index') # 給type對象增加兩個屬性title_banner, image_banner # 分別保存type種類首頁展示的文字商品信息和圖片商品信息 type.title_banner = title_banner type.image_banner = image_banner # 將購物車顯示數量設置為零 cart_count = 0 # 組織緩存的上下文 context = { 'types': types, 'index_banner': index_banner, 'promotion_banner': promotion_banner, 'cart_count': cart_count } # 設置緩存, 第一個參數是鍵名,第二個值,第三個是過期時間, 不設置過期時間,就是永不過期 cache.set('index_page_data', context, 3600)# 獲取登錄用戶后購物車商品的數目,先設置為零 cart_count = 0 # 獲取user user = request.user if user.is_authenticated(): # 用戶已登錄 conn = get_redis_connection('default') cart_key = 'cart_%d'%user.id cart_count = conn.hlen(cart_key) # 更新模板上下文 context.update(cart_count=cart_count) # 使用模板 return render(request, 'index.html', context)
這里既使用cache模塊將數據保存到redis中(已經在配置文件中將緩存數據庫設置為了redis), 也使用了django_redis模塊的get_redis_connection()方法進行保存數據, 個人理解:緩存這里和redis肯定建立的是長連接,使用get_redis_connection()可能建立的是短鏈接。但是直接使用cache,只可以使用cache,get()進行獲取數據, 使用cache.set()進行設置緩存. 但是,使用get_redis_connection(),可以自由使用redis的各種數據格式進行保存數據,更加靈活多變.