Redis use interface cache

A, Redis database description

1. Redis installed

"""
1、官网下载:安装包或是绿色面安装 (https://redis.io/)
2、安装并配置环境变量
"""

2. redis VS mysql

"""
redis: 内存数据库(读写快)、非关系型(操作数据方便、数据固定)
mysql: 硬盘数据库(数据持久化)、关系型(操作数据间关系、可以不同组合)

大量访问的临时数据,才有redis数据库更优
"""

3. redis VS memcache

"""
redis: 操作字符串、列表、字典、无序集合、有序集合 | 支持数据持久化(数据丢失可以找回(默认持久化,主动持久化save)、可以将数据同步给mysql) | 高并发支持
memcache: 操作字符串 | 不支持数据持久化 | 并发量小
"""

Second, the basic use of Redis

1. Start Service

# dump.rdb文件:(我们在哪启动的redis服务,就会在哪生成该文件,所以启动redis服务前,应该先切换到合适的位置)
    redis缓存中的数据将会保存到该文件
    
"""
1)前台启动服务(就是在终端启动,这个终端关了,服务也关了)
>: redis-server
2)后台启动服务 (就是在终端启动,这个终端关了,服务还在运行)
>: redis-server --service-start
3)通过配置文件启动服务
>: redis-server 配置文件的绝对路径
>: redis-server --service-start 配置文件的绝对路径
eg>: redis-server --service-start D:/redis/redis.conf
"""

2. Password Management

"""
1)提倡在配置文件中配置,采用配置文件启动后,就需要输入密码才有查看数据的权限
安装文件中的配置文件redis.windowsconf中:requirepass 密码

2)当服务启动后,并且连入数据库,可以再改当前服务的密码(该密码只对当前服务有效;服务重启,则密码重置,就是普通启动的话,密码会重置为空,通过配置文件启动的话,密码会重置为配置文件中的密码)
config set requirepass 新密码

3)连入数据库,查看当前服务密码密码
config get requirepass
"""

3. Redis client connection server

  • Redis is also a client a server, start the server, the client is connected to the server, database operations.
"""
1)默认连接:-h默认127.0.0.1,-p默认6379,-n默认0,-a默认无
>: redis-cli

书写连接参数时,一定要与前面的-h,-p等这些符号空一格。而mysql则不用空格
其中:-h 表示服务端IP,连接本机时就是127.0.0.1,也可以写成localhost
     -p 表示端口号
     -n 表示连接哪个数据库,默认从0到15个,共16个数据库
     -a 表示密码

2)完整连接:
>: redis-cli -h ip地址 -p 端口号 -n 数据库编号 -a 密码

3)先连接,后输入密码
>: redis-cli -h ip地址 -p 端口号 -n 数据库编号
>: auth 密码
"""

4. Close the Redis service

"""
1)当没有连接进服务端时,执行
>: redis-cli shutdown

2)当连接进服务端后,执行
>: shutdown
"""

5. Switch Database

'''
Redis默认从0到15个,共16个数据库

1)在连入数据库后,执行
>: select 数据库编号   (数据库编号就是0-15,当输入没有的数字类型的编号时,默认连接进0数据库,当输入不是数字的编号时,会报错)

'''

6. Data Persistence

"""
1)配置文件中的默认配置
save 900 1  # 超过900秒有1个键值对操作,会自动调用save完成数据持久化
save 300 10  # 超过300秒有10个键值对操作,会自动调用save完成数据持久化
save 60 10000  # 超过60秒有10000个键值对操作,会自动调用save完成数据持久化

2)安全机制
# 当redis服务不可控宕机,会默认调用一下save完成数据持久化

3)主动持久化
>: save  # 连入数据库时,主动调用save完成数据持久化,不用在save后面加括号

注:数据持久化默认保存文件 dump.rdb,保存路径默认为启动redis服务的当前路径
"""

Three, Redis data types and use

  • Since Redis non-relational databases, so use Redis, it is to operate all kinds of key-value
"""
数据类型:字符串、列表、哈希(字典)、无序集合、有序(排序)集合
    有序集合的应用:游戏排行榜
    
    
******************在终端中的使用方法*******************
    
字符串:
    set key value
    get key
    mset k1 v1 k2 v2 ...
    mget k1 k2 ...
    setex key exp value
    incrby key increment
    
列表:
    rpush key value1 value2 ...
    lpush key value1 value2 ...
    lrange key bindex eindex
    lindex key index
    lpop key | rpop key
    linsert key before|after old_value new_value
    
哈希:
    hset key field value
    hget key field
    hmset key field1 value1 field2 value2 ...
    hmget key field1 field2
    hkeys key
    hvals key
    hdel key field
    
集合:
    sadd key member1 member2 ...
    sdiff key1 key2 ...
    sdiffstore newkey key1 key2 ...
    sinter key1 key2 ...
    sunion key1 key2 ...
    smembers key
    spop key
    
有序集合:
    zadd key grade1 member1 grade2 member2 ...
    zincrby key grade member
    zrange key start end
    zrevrange key start end
"""

Four, python use Redis

1. Installation module redis

pip install redis

2. Use of Redis in python

  • There are two ways

1. 直接使用
import redis
r = redis.Redis(host='127.0.0.1', port=6379, db=1, password=None, decode_responses=True)

2. 以连接池的方式使用,这样就有类似线程池一样的作用
import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=1, max_connections=100, password=None, decode_responses=True)
r = redis.Redis(connection_pool=pool)

3. 使用方式:和终端中的使用方式基本一样

r.get(key) ...

3. Django project use Redis as a cache database

Why (1) Django project to use Redis

  • Although Django comes with cache management cachemodule, however, cache management is cached Django project, Django project when the program is closed, the cache will be automatically destroyed, so we need to use Redis as Django's cache database. Let cache management Redis database. Even if this is the Django project program is closed, the data cache remain.
  • Redis database can store strings, numbers and types of binary data, for the other objects in the python, can not be directly stored. Need to use Django own cache to process, store achieve complex objects.

Cache Module Application Redis (2) Django project

使用步骤:

# 1.将缓存存储位置配置到redis中:settings.py
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "DECODE_RESPONSES": True,
            "PSAAWORD": "",
        }
    }
}

# 2.操作cache模块直接操作缓存:views.py
from django.core.cache import cache  # 结合配置文件实现插拔式
# 存放token,可以直接设置过期时间
cache.set('token', 'header.payload.signature', 300)
# 取出token
token = cache.get('token')

4. Cache Interface

(1) What is the interface cache

1. 后台接口是提供数据库数据的,IO操作慢,可以将数据存储在缓存中,接口数据从缓存中调
2. 一般将大量访问(数据时效性要求不是很苛刻)的接口建立缓存
3. 接口缓存思想:数据先走缓存,有直接返回,没有走数据库(同步到缓存)

(2) Cache Interface Example

# Django项目中网站主页的轮播图展示的后端业务逻辑

from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from django.conf import settings
from utils.response import APIResponse
from . import models, serializers
from rest_framework.response import Response
from django.core.cache import cache
class BannerListViewSet(mixins.ListModelMixin, GenericViewSet):
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('-orders').all()[:settings.BANNER_COUNT]
    serializer_class = serializers.BannerModelSerializer

    # 自定义响应结果的格式
    # def list(self, request, *args, **kwargs):
    #     response = super().list(request, *args, **kwargs)
    #     return APIResponse(results=response.data)

    # 接口缓存
    def list(self, request, *args, **kwargs):
        data = cache.get('banner_cache')

        if not data:
            print('走了数据库')
            response = super().list(request, *args, **kwargs)
            cache.set('banner_cache', response.data)  # 不设置过期时间,缓存的更新在后台异步更新(celery异步框架)
            return response

        return Response(data)

Guess you like

Origin www.cnblogs.com/Mcoming/p/12173432.html