1.连接redis
字典形式连接redis
redis_info = {
"host":"192.168.1.1",#数据库地址
"password":"121111",#数据库密码
"db":15, #第几个数据库
"port"=6379 #默认端口号
}
r = redis.Redis(**redis_info,decode_responses=True)
#decode_responses=True 添加这个参数的话默认返回字符串
连接redis
conn = redis.Redis(host="192.168.1.1",password="1234533!",port=6379,db=15)
2.redis操作字符串(string)
存取字符串:(字符串是以key:value形式存储的)
r.set("error_count.13452678267",5) #存数据
获取数据:
r.get("error_count.18612532945").decode()#取数据
#print(r.get("error_count.13425676545").decode())
删除数据:
r.delete("error_count.13425261718")
设置key的失效时间:
r.set("token.18612532945","sdgsdgsgswtwetwdfs",20)
#第一个参数是key
#第二个参数是velues
#第三个参数可以指定一个key的失效时间,是多少秒
查看key的失效时间:
r.ttl("error_count.13425637281")#查看失效时间
#print(r.ttl("error_count.13425637281"))#查看失效时间,ttl不区分key的类型
查看key的类型:
r.type("error_count.13425627182")#查看key的类型
#print(r.type("error_count.13425627182"))#查看key的类型
查看key是否存在:
r.exists("error_count.13425162734")#查看key是否存在
#print("exists",r.exists("error_count.13425162734"))
3.redis操作hash
#结构
{
"class1": {
"xiaohong":1,
"xiaohong2":3
},
"class2":{
"xiaobai":1,
"xiaobai2":2
}
}
插入hash类型数据:
r.hset("class1","xiaohong",'{"id":1,"age":18}')
获取指定的值:
r.hget("class1","lilei") #取出指定的
获取所有的值:
r.hgetall("class1") #取出所有的值
删除指定的值:
r.hdel("class1","xiaohong") #删除指定的key
删除所有的值:
r.delete("class1")
对指定的key设置失效时间:
r.expire("class1",500) #对指定的key设置失效时间
查找指定的小key是否存在:
r.hexists("class1","xiaohong") #指定的小key是否存在
获取所有的value:
r.hvals("class1") #获取hash下面的所有的value
批量设置key:value
stus = {"zhangqi":"sdgsdg","zhoutingting":"sdgsgs","zhaoqin":"sgsg"}
r.hmset("class1",stus) #批量设置
批量设置values
stus = {"zhangqi":"sdgsdg","zhoutingting":"sdgsgs","zhaoqin":"sgsg"}
r.hmset("class1",stus) #批量设置
r.hset("class1",mapping=stus) #批量设置value
4.redis操作list
插入list类型数据:
r.lpush("students","weixiangjing2","xiaohei","xiaobai")#从开头增加数据
r.lpushx("students","zhulixiang") #如果这个key不存在,那么就不会新增
删除数据:
r.delete("students")#删除元素
r.lpop("students")) #删除末尾的元素
r.lrem("students",1,"xiaohei") #删除指定的元素,传0的话,删除所有的
获取所有数据:
r.lrange("students",0,-1)
指定下标获取元素:
r.lindex("students",0)
获取list长度:
r.llen("students") #取list的长度
指定的位置添加元素:
r.linsert("students","BEFORE","xiaohei","DAHUA")
#在指定的位置添加元素,要传key 位置(before/after) 哪个参数 实际你要插入的值
修改元素:
r.lset("students",0,"Zhulixiang") #修改指定下标的元素
5.redis操作set
插入set类型数据:
r.sadd("stu2","xiaohei","xiaozi","xiaobai") #添加
r.sadd("stu3","xiaohei","xiaolan","xiaobai") #添加
获取集合中的所有元素:
r.smembers("stu2") #返回这个集合里面所有的元素
随机删除一个元素:
r.spop("stu2") #随机删除一个元素
查找该元素是否在这个集合中:
r.sismember("stu2","xiaohei") #判断一个元素是否在这个集合里面
查找集合中有多少元素:
r.scard("stu2") #返回集合种有几个元素
获取两个集合的交集:
r.sinter("stu2","stu3") #两个集合取交集