redis相信大家都很熟悉了,和memcached一樣是一個(gè)高性能的key-value數(shù)據(jù)庫(kù),至于什么是緩存服務(wù)器,度娘都有很明白的介紹了,我在這里就不一一介紹了。
那我們一般什么情況下才會(huì)使用緩存服務(wù)器呢?可不是什么情況都需要的哦,一般來說是在需要頻繁對(duì)一個(gè)字段讀取的時(shí)候才會(huì)需要將這個(gè)字段放入到緩存服務(wù)器上,而且由于key-value數(shù)據(jù)庫(kù)一般只是放很簡(jiǎn)單的數(shù)據(jù),所以在選擇保存的對(duì)象的時(shí)候要注意選擇好。
下面我就來介紹如何在django中配置使用redis數(shù)據(jù)庫(kù),首先是先安裝redis了,在ubuntu中執(zhí)行下面這句命令:
#安裝redis服務(wù)器端
1
|
sudo apt - get install redis - server |
然后為了能在django中使用redis,還需要安裝redis for django的插件:
1
|
pip install django - redis |
這是一個(gè)開源的項(xiàng)目,github地址是https://github.com/niwibe/django-redis,感謝作者。
那么現(xiàn)在就是在django的settings中配置了。
1
2
3
4
5
6
7
8
9
10
11
12
|
caches = { 'default' : { 'backend' : 'redis_cache.cache.rediscache' , 'location' : '127.0.0.1:6379' , "options" : { "client_class" : "redis_cache.client.defaultclient" , }, }, } redis_timeout = 7 * 24 * 60 * 60 cubes_redis_timeout = 60 * 60 never_redis_timeout = 365 * 24 * 60 * 60 |
其實(shí)只是需要caches中的那幾條就可以了,后面這三句可以不需要的,只是我后面的例子里需要用到,我就在這里配置了。
好了,現(xiàn)在連接和配置都已經(jīng)完成了,那么在項(xiàng)目中該如何使用呢?接下來看下面這段例子吧。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
from django.conf import settings from django.core.cache import cache #read cache user id def read_from_cache( self , user_name): key = 'user_id_of_' + user_name value = cache.get(key) if value = = none: data = none else : data = json.loads(value) return data #write cache user id def write_to_cache( self , user_name): key = 'user_id_of_' + user_name cache. set (key, json.dumps(user_name), settings.never_redis_timeout) |
通過上面的這兩個(gè)方法就可以實(shí)現(xiàn)對(duì)redis的讀取操作了,只需要將需要的字段當(dāng)參數(shù)傳入到方法中就好了。
那么之前提到的memcached呢?其實(shí)也是一樣的配置:
1
2
3
4
5
6
|
caches = { 'default' : { 'backend' : 'django.core.cache.backends.memcached.memcachedcache' , 'location' : '127.0.0.1:11211' , } } |
當(dāng)然用法也是和我上面的例子是一樣的了。其實(shí)對(duì)于redis這樣的緩存服務(wù)器來說,配置都是很簡(jiǎn)單的,而具體的使用也不難,官網(wǎng)上面也有很多簡(jiǎn)單明了的例子可以供我們參考,只有一點(diǎn)需要注意的,那就是對(duì)于要將什么樣的信息保存到redis才是我們真正需要關(guān)心的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.pythontab.com/html/2014/pythonweb_1224/937.html