一.redis介绍
![image]()
二.下载安装
![image]()
安装
![image]()
三.redis服务的启动与关闭
1.启动服务器
方式一:
![image]()
方式二:
![image]()
![image]()
2.启动客户端
![image]()
四. python连接redis
1.安装模块:pip install redis
2.普通连接
![image]()
3.连接池连接(以模块导入的方式实现单例)
![image]()
![image]()
五.redis的基本使用
1.字符串操作
import redis
conn=redis.Redis()
# 1 set(name, value, ex=None, px=None, nx=False, xx=False)
conn.set('age',19)
ex,过期时间(秒)---->过期时间
px,过期时间(毫秒) ---->过期时间
conn.set('name','lyf',ex=3)
nx,如果设置为True,则只有name不存在时,当前set操作才执行, 值存在,就修改不了,执行没效果
conn.set('name','jack',nx=True)
xx,如果设置为True,则只有name存在时,当前set操作才执行,值存在才能修改,值不存在,不会设置新值
conn.set('name','jack',xx=True)
# 2 setnx(name, value)--->等同于conn.set('name','jack',nx=True)
# 3 setex(name, value, time)--->conn.set('name','lyf',ex=3)
# 4 psetex(name, time_ms, value)--->conn.set('name','lyf',px=3)
# 5 mset(*args, **kwargs)--》批量设置
conn.mset({'name1':'pyy','age1':20})
# 6 get(name)
print(conn.get('age1'))
# 7 mget(keys, *args)
print(conn.mget(['age1','age']))
print(conn.mget('name','age','age1'))
# 8 getset(name, value)
print(conn.getset('name','dsb'))
# 9 getrange(key, start, end)
print(conn.getrange('name',0,1)) # 取字节 ,前闭后闭
# 10 setrange(name, offset, value)
conn.setrange('name',1,'qqq') # dsb--->dqqq
# 11 setbit(name, offset, value) 独立用户统计
conn.setbit('name',1,0)
# 改的是比特位, 一个byte占8个比特位--》2进制---》10进制---》字符
# 12 getbit(name, offset)
print(conn.getbit('name',1))
# 13 bitcount(key, start=None, end=None)
# print(conn.bitcount('name',0,1)) # 数字指的是字节,不是比特位
# 14 strlen(name)
print(conn.strlen('name')) #长度:单位字节--》9
gbk编码一个中文占2个字节 utf-8编码 大部分一个中文占3个字节,生僻字可能占4
# 15 incr(self, name, amount=1)--->自增
conn.incr('age')
# 16 incrbyfloat(self, name, amount=1.0)
# 17 decr(self, name, amount=1)
conn.decr('age')
# 18 append(key, value)
conn.append('name','nb')
2.hash操作(hash即字典)
import redis
conn=redis.Redis()
# 1 hset(name, key, value)
conn.hset("userinfo",'name','彭于晏')
conn.hset("userinfo_01",mapping={'name':"刘亦菲",'age':18})
# 2 hmset(name, mapping)---》弃用了-->直接使用hset即可
conn.hmset("userinfo_02",mapping={'name':"刘亦菲",'age':18})
# 3 hget(name,key)
print(str(conn.hget('userinfo_01','name'),encoding='utf-8'))
print(str(conn.hget('userinfo_01','age'),encoding='utf-8'))
# 4 hmget(name, keys, *args)
print(conn.hmget('userinfo_01',['name','age']))
print(conn.hmget('userinfo_01','name','age'))
# 5 hgetall(name)--->慎用,获取所有
print(conn.hgetall('userinfo_01'))
# 6 hlen(name)
print(conn.hlen('userinfo_01')) # 2
# 7 hkeys(name)
print(conn.hkeys('userinfo_01')) # [b'name', b'age']
# 8 hvals(name)
print(conn.hvals('userinfo_01'))
# [b'\xe5\x88\x98\xe4\xba\xa6\xe8\x8f\xb2', b'18']
# 9 hexists(name, key)
print(conn.hexists('userinfo_01','name'))
print(conn.hexists('userinfo_01','height'))
# 10 hdel(name,*keys)
conn.hdel('userinfo_01','name')
# 11 hincrby(name, key, amount=1)
conn.hincrby('userinfo_01','age')
# 12 hincrbyfloat(name, key, amount=1.0)
# 13 hscan(name, cursor=0, match=None, count=None) hash类型无序
for i in range(1000):
conn.hset('hash_test','id_%s'%i,'鸡蛋%s号'%i)
# 分批获取,但是由于没有顺序,返回一个cursor,下次基于这个cursor再继续获取
res=conn.hscan('hash_test',0,count=20)
print(res)
res1=conn.hscan('hash_test',352,count=20)
print(res1)
print(len(res1[1]))
# 14 hscan_iter(name, match=None, count=None) #全取出所有值,分批取,不是一次性全取回来,减小内存占用
res=conn.hscan_iter('hash_test',count=10) # generator
print(res)
for item in res:
print(item)
print(conn.hgetall('hash_test'))
3.列表操作
import redis
conn=redis.Redis()
# 1 lpush(name,values) # 左添加
conn.lpush('girls','lyf','jack')
conn.rpush('girls','tony')
# 2 lpushx(name,value)
# 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最左边
conn.lpushx('girls','tony1')
conn.lpushx('girl','tony1')
# 3 llen(name)
print(conn.llen('girls'))
# 4 linsert(name, where, refvalue, value))
conn.linsert('girls','before','lyf','张杰')
conn.linsert('girls','after','lyf','lqz')
# 4 lset(name, index, value) 对name对应的list中的某一个索引位置重新赋值
conn.lset('girls',1,'tony')
# 5 r.lrem(name, count,value)
conn.lrem('girls',1,'tony') # 从左侧删第一个
conn.lrem('girls',-1,'tony') # 从右侧删第一个
conn.lrem('girls',0,'tony') # 全删
# 6 lpop(name)
res=conn.lpop('girls')
print(res)
# 7 lindex(name, index)
print(conn.lindex('girls',1))
# 8 lrange(name, start, end)
print(conn.lrange('girls',0,1)) # 前闭后闭
# 9 ltrim(name, start, end) ---》修剪,只保留起始到终止
conn.ltrim('girls',1,2)
# 10 rpoplpush(src, dst) # 从第一个列表的右侧弹出,放入第二个列表的左侧
# 11 blpop(keys, timeout) # 阻塞式弹出--》可以做消息队列
print(conn.blpop('girls',timeout=1))
# 12 brpoplpush(src, dst, timeout=0)
4. 通用操作
import redis
conn=redis.Redis()
# delete(*names)
conn.delete('name','name1','hash1')
# exists(name)
print(conn.exists('name'))
print(conn.exists('age'))
# keys(pattern='*') # 打印所有key
print(conn.keys()) # 打印所有key
print(conn.keys('us*')) # 打印所有带us的key
print(conn.keys('age?')) # 打印一个带age的key
# expire(name ,time)
conn.expire('age',3)
# rename(src, dst)
conn.rename('wife','girl')
# move(name, db))
conn.move('girl',3)
# randomkey() # 随机返回一个key
print(conn.randomkey())
# type(name)
print(conn.type('age1'))
print(conn.type('userinfo'))
5.管道
redis本身是不支持事务的,但是通过管道可以实现事务
import redis
pool = redis.ConnectionPool()
conn = redis.Redis(connection_pool=pool)
pipe = conn.pipeline(transaction=True)
pipe.multi() # 以后用pipe代替conn操作
pipe.set('name', 'jack')
raise Exception('报错')
pipe.set('role', 'nb')
pipe.execute() # 一次性执行多条命令
六.django中使用redis
1.自己写
# pool.py
import redis
POOL=redis.ConnectionPool(max_connections=10,host="localhost",port=6379)
# 任意位置使用
import redis
class TestView(APIView):
def get(self, requeste):
conn=redis.Redis(connection_pool=POOL)
print(conn.get('name'))
return Response('ok')
2.使用第三方
1.安装:pip install django-redis
2.在项目配置文件中
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},
"DECODE_RESPONSES": True,
# "PASSWORD": "123",
}
}
}
3.在使用位置
from django_redis import get_redis_connection
conn=get_redis_connection()
print(conn.get('name'))
# 一旦这么配置了,以后django的缓存也缓存到reids中了
cache.set('name','tony')
# 以后在django中,不用使用redis拿连接操作了,直接用cache做就可以了
# 不需要关注设置的值类型是什么
cache.set('name',['jack','tank']) # value值可以放任意数据类型