Redis

Redis是一种键值对类型的内存数据库,读写内存比读写硬盘快,我们在Django里面使用Redis非常方便,下面给出详细步骤

基于Ubuntu

1. 安装Redis和django-redis

sudo apt-get install redis-server

用 redis 做 Django的缓存系统的开源项目地址,有兴趣的看看:https://github.com/niwibe/django-redis
在这里我们把它装上,让Django和Redis手拉手交个朋友


pip install django-redis

2. 检查运行状态

ps -aux|grep redis
netstat -nlt|grep 6379

3. 修改seetings.py

#配置我是这么写的没问题
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': '127.0.0.1:6379',
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },
    },
}
#如果你的有问题,试试官方的写法 http://django-redis-chs.readthedocs.io/zh_CN/latest/#
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

4. 测试redis缓存

#进Django的shell里面
python manage.py shell
#从shell里面输入下面命令测试,不报错就正常,要是报错了要么没开启redis要么没装好,检查之前的步骤
from django.core.cache import cache
#写入key为key1,值为666的缓存,有效期30分钟
cache.set('key1', '666', 30*60)
cache.has_key('key1') #判断key为k是否存在
cache.get('key1')     #获取key为k的缓存

5. 更新和读取缓存

之前在Views.py视图函数里面,收到form提交的更新只是写入数据库,现在增加个更新缓存

#写入缓存
key = 'QuestionCache'
from django.core.cache import cache

def ask_question(request):

    question_category_name = request.POST['radio']
    question_title = request.POST['question_title']
    question_keywords = request.POST['question_keywords']
    question_text = request.POST['question_content']
    #没必要再设置这个字段了,models里面可以用auto_now自动获取当前时间的question_date = datetime.datetime.now()
    question_author = request.user
    joe = QuestionCategory.objects.get(category_name=question_category_name)
    qqqq = Question(question_category=joe,question_title=question_title,question_keywords=question_keywords,question_text=question_text,question_author=question_author)
    #写入数据库
    qqqq.save()

    #更新缓存
    cache.set(key, list(Question.objects.all().order_by('-question_date')))

    return redirect('pythonnav:blogindex_html')


# 读取缓存
def blogindex_html(request):
    #获取问题所有分类
    a = QuestionCategory.objects.all()
    es = []
    for e in a:
        es.append(e.category_name)

    # 展示所有的问题
    from django.core.paginator import Paginator
    from django.core.paginator import EmptyPage
    from django.core.paginator import PageNotAnInteger
    limit = 10  # 每页显示的记录条数

    #以前是直接从数据库查,每次都查数据多了要死人的,5555
    #现在先判断下,如果redis内存里面有就从内存读,不从数据库里查了,耶,感觉萌萌哒
    if cache.has_key(key):
        question = cache.get(key)
    else:
        question = Question.objects.all().order_by('-question_date')
    paginator = Paginator(question,limit)#实例化一个分页对象

    page = request.GET.get('page') #获取到页码

    try:
        q = paginator.page(page) #获取某夜对应的记录
    except PageNotAnInteger: #如果页码不是个整数
        q = paginator.page(1)#取第一页的记录
    except EmptyPage:#如果页码太大
        q = paginator.page(paginator.num_pages)#取最后一页的记录

Memcached

使用前准备工作
1.ubuntu下先安装:

sudo apt-get install memcached
pip install python-memcached

2.启动memcached

memcached -d -m 64 -u www -l 127.0.0.1 -p 11211 -c 1024 -P /tmp/memcached.pid

-d选项是启动一个守护进程,

-m是分配给Memcache使用的内存数量,单位是MB,我这里设的是64MB,

-u是运行Memcache的用户,我这里是www,

-l是监听的服务器IP地址,如果有多个地址的话,用空格分隔

-p是设置Memcache监听的端口,我这里设置了11211,最好是1024以上的端口,

-c选项是最大运行的并发连接数,默认是1024

-P是设置保存Memcache的PID文件,我这里是保存在 /tmp/memcached.pid,方便查看PID

3.查看memcached:

启动成功后,查看进程状态:

  ps -ef | grep memcached

查看11211端口状态:

  netstat -ntl

memcached的配置文件路径:

  /etc/sysconfig/memcached

4.测试memcache是否可以使用:
python manage.py shell 进入Django shell中

from django.core.cache import cache
    cache.set('key1', 'test')
    value = cache.get('key1')
    print value
#得到结果test

1.Django中seetings里面的设置

使用IP端口与Django交互
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

也可以通过一个本地的Unix socket file/tmp/memcached.sock来交互
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': 'unix:/tmp/memcached.sock',
    }
}

题外话:Memcached有一个非常好的特点就是可以让几个服务的缓存共享。 这就意味着你可以再几个物理机上运行Memcached服务,这些程序将会把这几个机器当做 同一个 缓存,从而不需要复制每个缓存的值在每个机器上。为了使用这个特性,把所有的服务地址放在LOCATION里面,用分号隔开或者当做一个list。

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': [
            '172.19.26.240:11211',
            '172.19.26.242:11211',
        ]
    }
}

2.Django中具体使用和Redis差不多

缓存数据

from django.core.cache import cache
def about(request):
    if cache.get('key1'):
        data = cache.get('key1')
    else:
        访问数据库,得到data
        cache.set('data')
    ...

每次进来,先查看cache中是否存在,若存在,直接获得该值,若不存在,则访问数据库,
得到数据之后,将其写入到cache之后,以便后续之用。

缓存整个页面。
可以使用Django提供的cache_page装饰函数,例如缓存about页面:
from django.views.decorators.cache import cache_page

@cache_page(60*30)
def about(request):
    ...

只需在view函数前加上cache_page装饰函数便可以该页面,cache_page的参数是缓存时间
这里设的是60s*30,即30分钟。同时也可以指定使用的缓存,通过cache参数来指定,例如:
@cache_page(60*30, cache='file_cache')则指定使用settings文件中CACHES中的file_cache
来缓存,若不指定,默认用default的来缓存。

更多参考:
http://python.usyiyi.cn/translate/django_182/topics/cache.html

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐