Django uses memcached and Redis as the cache configuration (Linux environment)

Source: Internet
Author: User
Tags memcached install django pip install django redis server

1 Installing memcached Installation with memcached1.1 (Linux)
sudo apt install memcached
Start
#方式一:service memcached start# 方式二:/usr/bin/memcached -u memcache -m 1024 -p 11222 -l 0.0.0.0 -d start
  • -D: This parameter is for memcached to run in the background
  • -M: Specifies how much memory is consumed. In M, the default is 64M.
  • -P: Specifies the port to occupy. The default port is 11211.
  • -L: Which IP address the other machine can connect to my server, if you want to connect other machines, you must set the-l 0.0.0.0
Detection starts successfully
ps aux|grep memcached# memcache 11025  0.0  0.1 326560  2372 ?  Ssl  Aug28   0:01 memcached -u memcache -m 512 -p 11211 -l 0.0.0.0 -d
1.2 Django Connection memcached1.2.1 Add a cached configuration to the ' setting.py ' file
# 缓存CACHES = {    ‘default‘: {        ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘,        ‘LOCATION‘: [            ‘172.19.26.240:11211‘,            ‘172.19.26.242:11211‘,        ]    }}

Note: The keys that you add are named in the following way

def default_key_func(key, key_prefix, version):    return ‘%s:%s:%s‘ % (key_prefix, version, key)

To modify, you can add the configuration ' Key_function ' in the setting.py file

CACHES = {    ‘default‘: {        ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘,        ‘LOCATION‘:  ‘172.19.26.240:11211‘,        ‘KEY_FUNCTION‘: lambda: key_prefix,version,key : ‘Django‘+key,    }}
After the 1.2.2 is configured, operate the cache in views:
from django.core.cache import cachedef index(request):    cache.set(‘username‘,‘django‘,60)    print(cache.get(‘username‘))    return HttpResponse(‘index‘)
2 Installing the Redis installation using redis2.1 (Linux)
    • Unzip the downloaded compressed file
tar zxvf redis-4.0.8.tar.gz
    • Replication: Recommended under "/usr/local/"
mv -r redis-4.0.8/* /usr/local/redis
    • Build and install
cd /usr/local/redismakemake install
Startup and Configuration
    1. Default mode Startup
2. Run Start
redis-server --port 6380  # 指定运行的端口号
    1. Configuration file Mode startup
redis-server /etc/redis/redis.conf
Client connection to Redis
    1. Interactive mode
redis-cli -h {host} -p {port}  # 会进入交互式环境
    1. Command mode
redis-cli -h {host} -p {port} {command}  # 直接执行一个命令,不进入交互式环境
Stop Redis Service
# 客户端关闭redis服务器,默认save即关闭时生成持久文件redis-cli shutdown nosave|save
2.2 Django Configuration on Redis Cache development machine installed Django-redis
pip install django-redis
Config file ' setting.py '
# 创建键时命名方式def KEY_FUNCTION(key, key_prefix, version):    return "django:" + key# redis缓存CACHES = {    ‘default‘: {        ‘BACKEND‘: ‘django_redis.cache.RedisCache‘,        # url格式 redis://[:password]@host:port/0        # 可以在url指定redis的密码,0表示低0个数据库        ‘LOCATION‘: ‘redis://127.0.0.1:6379/1‘,        ‘OPTIONS‘: {            "CLIENT_CLASS": ‘django_redis.client.DefaultClient‘,            ‘PASSWORD‘: ‘123456‘,        },        # 自定义键名命名规则        ‘KEY_FUNCTION‘: KEY_FUNCTION,    }}
To the View cache
# 通过装饰器对views进行缓存@cache_page(60 * 2)  # 过期时间为秒def cache(request):    return HttpResponse(‘cache‘)
Cache the entire station, set in setting
MIDDLEWARE = [    ‘django.middleware.cache.UpdateCacheMiddleware‘,    ‘django.middleware.common.CommonMiddleware‘,    ‘django.middleware.cache.FetchFromCacheMiddleware‘,]
To cache a template fragment
{% load cache %}<!DOCTYPE html>
The underlying cache API
>>>from django.core.cache import cache>>>cache.set(‘username‘, ‘django‘, 120)>>>True>>>cache.get(‘username‘)>>>‘django‘>>>cache.ttl(‘username‘)>>>101>>>cache.set_many({‘a‘: 1, ‘b‘: 2, ‘c‘: 3})>>>cache.get_many([‘a‘, ‘b‘, ‘c‘])>>>OrderedDict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])

Redis Server:

127.0.0.1:6379[1]> keys *1) "django:b"2) "django:c"3) "django:a"127.0.0.1:6379[1]>

Django uses memcached and Redis as the cache configuration (Linux environment)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.