0 前言
將處理計算的結果先臨時保存起來,下次使用的時候可以先直接使用,如果沒有這個備份的數據,重新進行計算處理。
將緩存數據保存在內存中 (本項目中保存在redis中)
cache注意事項:
1)如果修改了數據庫的數據,直接刪除緩存;
2)緩存要設置有效期。
相關django文檔:Django緩存
1.設置緩存
# http://127.0.0.1:8000
class IndexView(View):'''首頁'''def get(self, request):'''顯示首頁'''# 嘗試從緩存中獲取數據context = cache.get('index_page_data')if context is None:print('設置緩存')# 緩存中沒有數據# 獲取商品的種類信息types = GoodsType.objects.all()# 獲取首頁輪播商品信息goods_banners = IndexGoodsBanner.objects.all().order_by('index')# 獲取首頁促銷活動信息promotion_banners = IndexPromotionBanner.objects.all().order_by('index')# 獲取首頁分類商品展示信息for type in types: # GoodsType# 獲取type種類首頁分類商品的圖片展示信息image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')# 獲取type種類首頁分類商品的文字展示信息title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')# 動態給type增加屬性,分別保存首頁分類商品的圖片展示信息和文字展示信息type.image_banners = image_bannerstype.title_banners = title_bannerscontext = {'types': types,'goods_banners': goods_banners,'promotion_banners': promotion_banners}# 設置緩存# key value timeoutcache.set('index_page_data', context, 3600)# 獲取用戶購物車中商品的數目user = request.usercart_count = 0if user.is_authenticated():# 用戶已登錄conn = get_redis_connection('default')cart_key = 'cart_%d'%user.idcart_count = conn.hlen(cart_key)# 組織模板上下文,context中存在則更新,不存在則添加context.update(cart_count=cart_count)# 使用模板return render(request, 'index.html', context)
在商品good應用的view視圖中,設置緩存。
緩存的鍵:index_page_data
緩存的值:context
context = {'types': types,'goods_banners': goods_banners,'promotion_banners': promotion_banners}
注意,獲取用戶購物車中商品的數目cart_count并未加入緩存,因為購物車模塊只有用戶登錄之后才會有!
2.獲取緩存
settings.py中設置緩存
# Django的緩存配置
CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://172.16.179.142:6379/9","OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",}}
}
Redis數據庫中查詢緩存
3.更新緩存
如果管理員在后臺對首頁的商品數據進行更改,則需要在調用save_model和delete.model的同時,更新緩存。