详细介绍
redis介绍
mysql是一个软件,帮助开发者对一台机器的硬盘进行操作
redis是一个软件,帮助开发者对一台机器的内存进行操作
缓存,命中,优先去redis中获取
特点:
持久化 AOF(做快照,定时保存),RDB(把所有的记录和命令做记录)
单进程,单线程
5大数据类型:字符串,字典,列表,集合,有序集合
-
安装:
redis软件
第一种方式:yum安装yum install redis redis-server /etc/redis.conf
第二种方式:
下载redis包1.wget http://download.redis.io/releases/redis-3.0.6.tar.gz 解压 2.tar xzf redis-3.0.6.tar.gz
切换到解压目录
3.cd redis-3.0.6
编译一下
4.make
修改配置文件redis.conf:
bind 0.0.0.0 port 6379 requirepass dskjfsdf
起redis服务
5./src/redis-server redis.conf 默认端口:6379
python安装redis的模块
pip3 install redis
-
基本使用:
1)创建连接
a. import redis 创建连接 conn = redis.Redis(host='47.94.172.250',port=6379,password='luffy1234') conn.set('x1','wanghuaqiang',ex=5) val = conn.get('x1') print(val) """ #在Redis中设置值,默认不存在则创建,存在则修改 r.set('name', 'zhangsan') '''参数: set(name, value, ex=None, px=None, nx=False, xx=False) ex,过期时间(秒) px,过期时间(毫秒) nx,如果设置为True,则只有name不存在时,当前set操作才执行,同setnx(name, value) xx,如果设置为True,则只有name存在时,当前set操作才执行''' """ b. 连接池(可采用单例模式放入一个py文件中) import redis pool = redis.ConnectionPool(host='10.211.55.4', port=6379,password='luffy1234',max_connections=1000) conn = redis.Redis(connection_pool=pool) conn.set('foo', 'Bar') 连接池注意:连接池只创建一次
2)自定义连接池
redis_pool.py
import redis POOL = redis.ConnectionPool(host='10.211.55.4', port=6379,password='luffy1234',max_connections=1000)
import redis from django.shortcuts import render,HttpResponse from utils.redis_pool import POOL def index(request): conn = redis.Redis(connection_pool=POOL) conn.hset('kkk','age',18) return HttpResponse('设置成功') def order(request): conn = redis.Redis(connection_pool=POOL) conn.hget('kkk','age') return HttpResponse('获取成功')
3)全栈缓存
redis配置 setting.pyMIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', #更新缓存 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', #获取缓存 ] CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } } }
from django.shortcuts import render,HttpResponse import time def index(request): ctime = str(time.time()) return HttpResponse(ctime) def order(request): ctime = str(time.time()) return HttpResponse(ctime)
4)单独视图缓存
方式一:
from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): ...
方式二:
from django.views.decorators.cache import cache_page urlpatterns = [ url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)), ]
示类:
# redis配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } } } # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', # 'LOCATION': '/var/tmp/django_cache', # } # } # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 'LOCATION': '127.0.0.1:11211', # } # }
from django.shortcuts import render,HttpResponse import time from django.views.decorators.cache import cache_page from rest_framework.throttling import SimpleRateThrottle @cache_page(60 * 15) def index(request): ctime = str(time.time()) return HttpResponse(ctime) def order(request): return render(request,'order.html')
5)局部页面
配置:setting.py
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "密码", } } }
使用:views.py
import redis from django.shortcuts import render,HttpResponse from django_redis import get_redis_connection def index(request): conn = get_redis_connection("default") return HttpResponse('设置成功') def order(request): conn = get_redis_connection("back") return HttpResponse('获取成功')
html
''' a. 引入TemplateTag {% load cache %} b. 使用缓存 {% cache 5000 缓存key %} 缓存内容 {% endcache %} {% load cache %} ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ time }}</h1> <h1>{{ time }}</h1> {% cache 10 c1 %} <h1>{{ time }}</h1> {% endcache %} </body> </html>
6)存放位置
此缓存将内容保存至内存的变量中
# 配置: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } # 注:其他配置同开发调试版本
此缓存将内容保存至文件
# 配置: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tmp/django_cache', } } # 注:其他配置同开发调试版本
此缓存将内容保存至数据库
# 配置: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', # 数据库表 } } # 注:执行创建表命令 python manage.py createcachetable
7) redis特点
a. 持久化 b. 单进程、单线程 c. 5大数据类型 redis={ k1:'123', 字符串 k2:[1,2,3,4,4,2,1], 列表 k3:{1,2,3,4}, 集合 k4:{name:123,age:666}, 字典 k5:{('alex',60),('eva-j',80),('rt',70),},有序集合 }
8)使用字典:
1- 基本操作 import redis conn = redis.Redis(host='127.0.0.1',port=6379,password='') redis = { k4:{ name = "long", age = 18 } } 字典放值 '''第一种写法''' conn.hmset("k4",{"name":"long","age":18}) conn.mget("k4",["name","age"]) conn.hmget("k4","name","age") '''第二种''' conn.hset("k4","name","long") conn.hset("k4","age",18) val = conn.hget("k4","name") 字典取值 '''获取所有数据''' val = conn.hgetall("k4") '''计数器''' conn.hincrby('k4','age',amount=-1) 给age减1 conn.hincrbyfloat('k4','age',amount=0.1) 浮点运算 '''生成器''' ret = conn.scan_iter("k4") for item in ret: print(item) ret = conn.hscan_iter("k4",count=100) for item in ret: print(item) (b'name', b'long') (b'age', b'17') - 慎重使用hgetall, 优先使用 hscan_iter - 计数器 注意事项:redis操作时,只有第一层value支持:list,dict ....
9)列表(队列)
'''从右往左推''' # conn.lpush('k1',1) # conn.lpush('k1',2) '''从左往右推''' # conn.rpush('k1',1) # conn.rpush('k1',2) '''从左拿值''' # conn.lpop('k1') '''从右拿值''' # conn.rpop('k1') '''若有值就取走没值就等待timeout秒,不写就一直等(阻塞)''' # conn.blpop('k1',timeout=10) '''迭代器''' # conn.lpush('k1',*[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7]) # ret = conn.lrange('k1',0,1) # 0-100 可以不停的取 # print(ret) # [b'9', b'8', b'7', b'6', b'5', b'4', b'3', b'2', b'1', b'9', b'8', b'7', b'6', b'5', b'4', b'3', b'2', b'1'] '''自定义列表生成器''' # def list_iter(key,count = 1): # index = 0 # while True: # date_list = conn.lrange(key,index,index+count-1) # if not date_list: # break # index += count # for item in date_list: # yield item # date = list_iter('k1',count=3) # for item in date: # print(item)
10)事务(一次发送多个命令)
pipe = conn.pipeline(transaction=True) pipe.multi() pipe.set('k2','123') pipe.hset('k3','n1',333) pipe.lpush('k5',*[1,2,3])