一 简介
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步

支持的数据类型(5大数据类型)

redis={ k1:'123', 字符串 k2:[1,2,3,4], 列表/数组 k3:{1,2,3,4} 集合 k4:{name:lqz,age:12} 字典/哈希表 k5:{('lqz',18),('egon',33)} 有序集合 } 特点:
可以持久化 单线程,单进程
安装和使用:
安装模块:pip3 intall redis
from redis import Redis from redis import ConnectionPool
Redis实例化产生对象,就是拿到一个redis的连接
conn=Redis()
操作redis(value部分都是以byte格式存储)
ret=conn.get('name') print(ret) pool=ConnectionPool(host='127.0.0.1',port=6379,max_connections=100) conn=Redis(connection_pool=pool) print(conn.get('name')) 添加数据
conn.set('age',20) 获取数据
ret=conn.get('age') print(ret) 设置数据,多少秒后删除(k,s,v)
conn.setex('xxx',5, 'ppp') 批量设置(传字典)mset(已存在键值会覆盖)
conn.mset({'name':'wy','age':20,'height':180}) 批量获取mget
print(conn.mget(['name','height']))
从某个位置开始,有只则覆盖,无值则追加
conn.setrange('name',1,'xx') incr 自增(文章阅读数,网站访问量的统计)
conn.incr('age',amount=2) decr 自减
conn.decr(name='age',amount=2)
append 无则新建,有则追加
conn.append('name','hhhhh') hash操作hset 无则添加,有则修改
conn.hset('hash1','k1','value1') 批量设置
conn.hmset('hash2',{'name':'qlz','age':18}) ȡֵ
print(conn.hget('hash1','k1')) 批量取值
print(conn.hmget('hash2',['name','age'])) print(conn.hmget('hash2','name','age')) 取全部
print(conn.hgetall('hash2')[b'name']) 字段条数
print(conn.hlen('hash1')) 删除
conn.hdel('hash1','k1') 自增
conn.hincrby('hash1','age',amount=1) 重点: hscan 、hscan_iter
for i in range(10000): conn.hset('hash3','key%s'%i,'value%s'%i) 从0开始取一百位
print(conn.hscan('hash3',0,count=100)) hscan_iter:获取字典所有数据的时候,推荐用这个,而不用 hgetall
print(conn.hscan_iter('hash3')) for i in conn.hgetall('hash3'): print(i) for i in conn.hscan_iter('hash3',100): print(i) redis之列表操作加在第一个位置
conn.lpush('list1','13') 加在最后一个位置
conn.rpush('list1','11') 表的数据条数
print(conn.llen('list1')) 找到的第一个12的前面插入999
conn.linsert('list1','BEFORE',12,999) 找到的第一个12的后面插入666
conn.linsert('list1','AFTER',12,666) 从0开始,第五位插入
conn.lset('list1','4',123) 删除第几个值为多少的元素
conn.lrem('list1',1,12) 根据索引取值
print(conn.lindex('list1',11)) 1,3 前后都是闭区间
print(conn.lrange('list1',1,3)) blpop 重点掌握删除并返回删除的值
print(conn.lpop('list1')) 没有值可以阻塞住,可以实现分布式
print(conn.blpop('list1'))# 没有值时不手动结束,会一直在这等到有值再运行 获取列表中所有值:
for i in range(1000): conn.lpush('list1',i) print(conn.lrange('list1',0,conn.llen('list1'))) def scan_list(name,count=10): index=0 while True: data_list=conn.lrange(name,index,count+index-1) if not data_list: return index+=count for item in data_list: yield item print(conn.lrange('list1',0,100)) print('------') for item in scan_list('list1',5): print('---') print(item) 删除age
conn.delete('age') 判断k1是否存在,返回1 or 0
print(conn.exists('k1')) 单个字符匹配
print(conn.keys('k?')) 模糊匹配(h开头)
print(conn.keys('h*')) 重命名
conn.rename('hash1','xxx') print(conn.type('list1')) 在django中使用redis
方式一
新建一个py文件,在视图类中导入
utils>redis_pool:
import redis Pool=redis.ConnectionPool(host='127.0.0.1',port=6379,max_connections=100)
views:
from django.shortcuts import render,HttpResponse # Create your views here. from redis import Redis from utils.redis_pool import Pool conn=Redis(connection_pool=Pool) def index(request): ret=conn.get('name') print(ret) return HttpResponse('ok')
安装django-redis模块
pip3 install django-redis
setting里配置:
# 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": "123", } } } views:
from django_redis import get_redis_connection conn = get_redis_connection('default') print(conn.hgetall('xxx')) 管道
redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。
import redis pool = redis.ConnectionPool(host='10.211.55.4', port=6379) r = redis.Redis(connection_pool=pool) # pipe = r.pipeline(transaction=False) pipe = r.pipeline(transaction=True) pipe.multi() pipe.set('name', 'alex') pipe.set('role', 'sb') pipe.execute()