文成小盆友python-num11-(2) python操作Memcache Redis
本部分主要内容:
python操作memcache
python操作redis
一.python 操作 memcache
memcache是一套分布式的高速缓存系统,由LiveJournal的Brad Fitzpatrick开发,但目前被许多网站使用以提升网站的访问速度,尤其对于一些大型的、需要频繁访问数据库的网站访问速度提升效果十分显著。这是一套开放源代码软件,以BSD license授权发布。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。
1.首先学会安装memcache以及一些简单的使用
下载memcache:
http://memcached.org/downloads -- 中找到稳定版本下载
安装如下:
tar -zxvf memcached-1.x.x.tar.gz cd memcached-1.x.x ./configure && make && make test && sudo make install 依赖libevent yum install libevent-devel apt-get install libevent-dev
启动如下:
memcached -d -m 10 -u root -l 92.168.1.100-p 11211 -c 256 -P /tmp/memcached.pid 参数说明: -d 是启动一个守护进程 -m 是分配给Memcache使用的内存数量,单位是MB -u 是运行Memcache的用户 -l 是监听的服务器IP地址 -p 是设置Memcache监听的端口,最好是1024以上的端口 -c 选项是最大运行的并发连接数,默认是1024,按照你服务器的负载量来设定 -P 是设置保存Memcache的pid文件
Memcached命令
存储命令: set/add/replace/append/prepend/cas 获取命令: get/gets 其他命令: delete/stats..
2.安装python操作memcache的模块
python操作Memcached使用Python-memcached模块 下载安装:https://pypi.python.org/pypi/python-memcached #或者直接 pip3 install python-memcached
3.python操作memcache
- 首次链接测试:
# -*- coding:utf-8 -*- #Author:wencheng.zhao # import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 debug = True 表示运行出现错误时,现实错误信息,上线后移除该参数。 mc.set("name","zhaowencheng") #set命名插入一条数据 ret = mc.get("name") #get命令获取刚才的数据 print(ret) #打印结果验证是否链接成功 ##输出结果 zhaowencheng
- 集群的支持
python-memcached模块原生支持集群操作,其原理是在内存维护一个主机列表,且集群中主机的权重值和主机在列表中重复出现的次数成正比
如下列表以及对应的权重:
主机 权重 1.1.1.1 1 1.1.1.2 2 1.1.1.3 3 那么在内存中主机列表为: host_list = ["1.1.1.1", "1.1.1.2", "1.1.1.2", "1.1.1.3", "1.1.1.3", "1.1.1.3", ]
如果用户根据如果要在内存中创建一个键值对(如:k1 = "v1"),那么要执行一下步骤:
- 根据算法将 k1 转换成一个数字
- 将数字和主机列表长度求余数,得到一个值 N( 0 <= N < 列表长度 )
- 在主机列表中根据 第2步得到的值为索引获取主机,例如:host_list[N]
- 连接 将第3步中获取的主机,将 k1 = "v1" 放置在该服务器的内存中
请看具体实现代码:
mc = memcache.Client([('1.1.1.1:11211', 1), ('1.1.1.2:11211', 2), ('1.1.1.3:11211', 1)], debug=True) mc.set('k1', 'v1')
- add命令
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 mc.add("address","beijing") print(mc.get("address")) #输出为 beijing ########### #如果药添加的key意境存在则会报错内容如下: MemCached: while expecting 'STORED', got unexpected response 'NOT_STORED'
- replace
修改某个key的值-如果key不存在则报异常:
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 mc.replace("name","wencheng.zhao") print(mc.get("name")) #显示结果如下: wencheng.zhao Process finished with exit code 0 ##如果药修改的key不存在则会报错 MemCached: while expecting 'STORED', got unexpected response 'NOT_STORED'
- set 和 set_multi
set 设置一个键值对,如果key不存在,则创建,如果key存在,则修改
set_multi 设置多个键值对,如果key不存在,则创建,如果key存在,则修改
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 mc.set("name","zhaowencheng") #set命名插入一条数据 mc.set_multi({"name":"zhaowencheng","address":"Beijing"}) #内部为字典模式
- get 和 get_multi
get 获取一个键值对
get_multi 获取多一个键值对
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 mc.set("name","zhaowencheng") #set命名插入一条数据 mc.set_multi({"name":"zhaowencheng","address":"Beijing"}) print(mc.get("name")) print(mc.get_multi(["name","address"])) #获得的结果以字典的方式存储 ##显示如下: zhaowencheng {'name': 'zhaowencheng', 'address': 'Beijing'} Process finished with exit code 0
- append 和 prepend
append 修改指定key的值,在该值 后面 追加内容
prepend 修改指定key的值,在该值 前面 插入内容
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 mc.set("name","zhaowencheng") #set命名插入一条数据 mc.set_multi({"name":"zhaowencheng","address":"Beijing"}) mc.append("name","_zhao_after") mc.prepend("address","B_before_") print(mc.get("name")) print(mc.get_multi(["name","address"])) ### zhaowencheng_zhao_after {'address': 'B_before_Beijing', 'name': 'zhaowencheng_zhao_after'} Process finished with exit code 0
- decr 和 incr
incr 自增,将Memcached中的某一个值增加 N ( N默认为1 )
decr 自减,将Memcached中的某一个值减少 N ( N默认为1 )
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 mc.set_multi({"name":"zhaowencheng","age":23,"address":"bejing"}) print(mc.get_multi(["name","age","address"])) mc.incr("age") print(mc.get_multi(["name","age","address"])) mc.decr("age") print(mc.get_multi(["name","age","address"])) #显示如下: {'age': 23, 'name': 'zhaowencheng', 'address': 'bejing'} #原来的年龄 23 {'age': 24, 'name': 'zhaowencheng', 'address': 'bejing'} #自增1之后 24 {'age': 23, 'name': 'zhaowencheng', 'address': 'bejing'} #自减1之后 23
指定自增(减的值)
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True) #链接客户端 提供主机地址以及端口号默认11211 mc.set_multi({"name":"zhaowencheng","age":23,"address":"bejing"}) print(mc.get_multi(["name","age","address"])) mc.incr("age",10) print(mc.get_multi(["name","age","address"])) mc.decr("age",10) print(mc.get_multi(["name","age","address"])) ###显示如下 {'address': 'bejing', 'name': 'zhaowencheng', 'age': 23} {'address': 'bejing', 'name': 'zhaowencheng', 'age': 33} {'address': 'bejing', 'name': 'zhaowencheng', 'age': 23} Process finished with exit code 0
- gets 和 cas
如商城商品剩余个数,假设改值保存在memcache中,product_count = 900
A用户刷新页面从memcache中读取到product_count = 900
B用户刷新页面从memcache中读取到product_count = 900
如果A、B用户均购买商品
A用户修改商品剩余个数 product_count=899
B用户修改商品剩余个数 product_count=899
如此一来缓存内的数据便不在正确,两个用户购买商品后,商品剩余还是 899
如果使用python的set和get来操作以上过程,那么程序就会如上述所示情况!
如果想要避免此情况的发生,只要使用 gets 和 cas 即可,如:
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True,cache_cas=True) #链接客户端 提供主机地址以及端口号默认11211 mc.set("product_count",888) v = mc.gets("product_count") print(v) mc.cas('product_count', "888") ##没有报错: 888
如下则会报错:
import memcache #导入模块 mc = memcache.Client(['192.168.1.100:11211'],debug=True,cache_cas=True) #链接客户端 提供主机地址以及端口号默认11211 mc.set("product_count",888) v = mc.gets("product_count") mc.set("product_count","234") mc.cas('product_count', "888") ### MemCached: while expecting 'STORED', got unexpected response 'EXISTS' Process finished with exit code 0
本质上每次执行gets时,会从memcache中获取一个自增的数字,通过cas去修改gets的值时,会携带之前获取的自增值和memcache中的自增值进行比较,如果相等,则可以提交,如果不想等,那表示在gets和cas执行之间,又有其他人执行了gets(获取了缓冲的指定值), 如此一来有可能出现非正常数据,则不允许修改。
二.python操作redis
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
1.redis 的安装
wget http://download.redis.io/releases/redis-3.0.6.tar.gz tar xzf redis-3.0.6.tar.gz cd redis-3.0.6 make
启动服务端
src/redis-server
启动客户端-链接
2. 安装Python操作Redis的模块
sudo pip install redis or sudo easy_install redis or 源码安装 详见:https://github.com/WoLpH/redis-py
API使用
redis-py 的API的使用可以分类为:
- 连接方式
- 连接池
- 操作
- String 操作
- Hash 操作
- List 操作
- Set 操作
- Sort Set 操作
- 管道
- 发布订阅
操作模式
redis-py提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令,Redis是StrictRedis的子类,用于向后兼容旧版本的redis-py。
####################### import redis r = redis.Redis(host='192.168.1.100',port=6379) r.set("address","beijing") print(str(r.get("address"),encoding="utf-8")) ##显示 beijing Process finished with exit code 0
连接池
redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.set("age",23) print(str(r.get("age"),encoding="utf-8")) ###显示 23
3.python操作redis
String操作 :redis中的String在在内存中按照一个name对应一个value来存储。如图:
- set
set(name, value, ex=None, px=None, nx=False, xx=False)
在Redis中设置值,默认,不存在则创建,存在则修改
参数:
ex,过期时间(秒)
px,过期时间(毫秒)
nx,如果设置为True,则只有name不存在时,当前set操作才执行
xx,如果设置为True,则只有name存在时,岗前set操作才执行
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.set("name","zhaowencheng") print(str(r.get("name"),encoding="utf-8")) #显示 zhaowencheng Process finished with exit code 0
- setnx(name, value)
设置值,只有name不存在时,执行设置操作(添加)
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.set("name","zhaowencheng") print(str(r.get("name"),encoding="utf-8")) r.setnx("name","zzzz") #因为原先有name所有没有修改 r.setnx("phone",12321232123) #原先没有phone这个key,所以添加了 print(str(r.get("name"),encoding="utf-8")) print(str(r.get("phone"),encoding="utf-8")) ##显示 zhaowencheng zhaowencheng 12321232123 Process finished with exit code 0
- setex(name, value, time)
设置值
参数:
time,过期时间(数字秒 或 timedelta对象)
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.setex("aa","zhaozhaozhao",30) print(str(r.get("aa"),encoding="utf-8"))
- psetex(name, time_ms, value)
# 设置值
# 参数:
# time_ms,过期时间(数字毫秒 或 timedelta对象)
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.setex("aa","zhaozhaozhao",30) print(str(r.get("aa"),encoding="utf-8"))
- mset(*args, **kwargs)
批量设置值
如:
mset(k1='v1', k2='v2')
或
mget({'k1': 'v1', 'k2': 'v2'})
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) # r.setex("aa","zhaozhaozhao",30) # print(str(r.get("aa"),encoding="utf-8")) r.mset(name='zhaowencheng',address="beijing",dd='ssssss') #直接赋值 r.mset({'a':'b','c':'d'}) #字典方式 print(str(r.get("dd"),encoding="utf-8")) print(str(r.get("a"),encoding="utf-8")) ## 显示 ssssss b Process finished with exit code 0
- get -(如上实例)
- mget(keys, *args)
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.mset(name='zhaowencheng',address="beijing",dd='ssssss') r.mset({'a':'b','c':'d'}) print(r.mget('a','c')) print(r.mget(['a','c'])) ###显示 [b'b', b'd'] [b'b', b'd'] Process finished with exit code 0
- getset(name, value)
设置新值并获取原来的值:
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.mset(name='zhaowencheng',address="beijing",dd='ssssss') r.mset({'a':'b','c':'d'}) v = r.getset("a","bbbb") print(v) v1 = r.get("a") print(v1) # 显示如下: b'b' b'bbbb' Process finished with exit code 0
- getrange(key, start, end)
获取子序列(根据字节获取,非字符)
参数:
name,Redis 的 name
tart,起始位置(字节)
end,结束位置(字节)
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.mset(name='zhaowencheng',address="beijing",dd='ssssss') v = r.getrange("name",1,3) print(v) ###显示如下 b'hao' Process finished with exit code 0
- setbit(name, offset, value)
对name对应值的二进制表示的位进行操作
参数:
name,redis的name
offset,位的索引(将值变换成二进制后再进行索引)
value,值只能是 1 或 0
#如果在Redis中有一个对应: n1 = "foo", #那么字符串foo的二进制表示为:01100110 01101111 01101111 #所以,如果执行 setbit('n1', 7, 1),则就会将第7位设置为1, #那么最终二进制则变成 01100111 01101111 01101111,即:"goo" import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.set("n1","foo") v = r.get("n1") print(v) r.setbit("n1",7,1) v = r.get("n1") print(v) #显示 b'foo' b'goo' Process finished with exit code 0
- getbit(name, offset)
获取name对应的值的二进制表示中的某位的值 (0或1)
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.setbit("n1",7,1) v = r.getbit("n1",7) print(v) #显示 1
- bitcount(key, start=None, end=None)
获取name对应的值的二进制表示中的某位的值 (0或1)# 获取name对应的值的二进制表示中 1 的个数
参数:
key,Redis的name
start,位起始位置
end,位结束位置
pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.setbit("n1",7,1) v = r.bitcount("n1",1,7) print(v) #显示 12
- bitop(operation, dest, *keys)
获取多个值,并将值做位运算,将最后的结果保存至新的name对应的值
参数:
operation,AND(并) 、 OR(或) 、 NOT(非) 、 XOR(异或)
dest, 新的Redis的name
*keys,要查找的Redis的name
# 如:
bitop("AND", 'new_name', 'n1', 'n2', 'n3')
# 获取Redis中n1,n2,n3对应的值,然后讲所有的值做位运算(求并集),然后将结果保存 new_name 对应的值中
import redis pool = redis.ConnectionPool(host='192.168.1.100',port=6379) r = redis.Redis(connection_pool=pool) r.mset(n1="foo",n2="goo",n3="soo") vvv = r.bitop("AND", 'vvvv', 'n1', 'n2', 'n3') print(vvv) #获取Redis中n1,n2,n3对应的值,然后讲所有的值做位运算(求并集),然后将结果保存 new_name 对应的值中 #显示如下 3
- strlen (name)
返回name对应的字节的长度
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) print(r.get("name")) ret = r.strlen("name") print(ret) #显示如下: b'zhaowencheng' 12 Process finished with exit code 0
- incrbyfloat(self, name, amount=1.0)
自增 name对应的值,当name不存在时,则创建name=amount,否则,则自增。
参数:
name,Redis的name
amount,自增数(必须是整数)
- incrbyfloat(self, name, amount=1.0)
自增 name对应的值,当name不存在时,则创建name=amount,否则,则自增。
参数:
name,Redis的name
amount,自增数(浮点型)
使用方法相同
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) print(r.get("age")) r.incr("age") print(r.get("age")) #已经自增1 r.incr("num-num",amount=1) print(r.get("num-num")) #显示如下: b'26' b'27' b'1' Process finished with exit code 0
- dcer(self,name,amount=1)
自减 name对应的值,当name不存在时,则创建name=amount,否则,则自减。
参数:
name,Redis的name
amount,自减数(整数)
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) print(r.get("age")) print(r.decr(name="age")) ## 显示如下: b'25' 24 Process finished with exit code 0
append(key, value)
在redis name对应的值后面追加内容
参数:
key, redis的name
value, 要追加的字符串
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) print(r.get("name")) r.append("name","_hello") print(r.get("name")) ##显示如下: b'zhaowencheng' b'zhaowencheng_hello' Process finished with exit code 0
Hash 操作 redis中的Hash 在内存中的存储格式如下图所示:
- hset(name, key, value)
# name对应的hash中设置一个键值对(不存在,则创建;否则,修改)
# 参数:
# name,redis的name
# key,name对应的hash中的key
# value,name对应的hash中的value
# 注:
# hsetnx(name, key, value),当name对应的hash中不存在当前key时则创建(相当于添加)
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.hset("hash-name","k1","v1")
- hmset(name, mapping)
# 在name对应的hash中批量设置键值对
# 参数:
# name,redis的name
# mapping,字典,如:{'k1':'v1', 'k2': 'v2'}
# 如:
# r.hmset('xx', {'k1':'v1', 'k2': 'v2'})
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.hmset("hash-name1",{"k1":"v1","k2":"v2"})
- hget(name,key)
# 在name对应的hash中获取根据key获取value
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.hset("hash-name","k1","v1") print(r.hget("hash-name","k1")) #显示如下: b'v1' Process finished with exit code 0
- hmget(name, keys, *args)
# 在name对应的hash中获取多个key的值
# 参数:
# name,reids对应的name
# keys,要获取key集合,如:['k1', 'k2', 'k3']
# *args,要获取的key,如:k1,k2,k3
# 如:
# r.mget('xx', ['k1', 'k2'])
# 或
# print r.hmget('xx', 'k1', 'k2')
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2"}) print(r.hmget("hash-name1",["k1","k2"])) print(r.hmget("hash-name1","k1","k2")) #显示如下: [b'v1', b'v2'] [b'v1', b'v2'] Process finished with exit code 0
- hgetall(name)
获取name对应
hash
的所有键值
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2"}) print(r.hgetall("hash-name1")) #显示如下: {b'k1': b'v1', b'k2': b'v2'} Process finished with exit code 0
- hlen(name)
# 获取name对应的hash中键值对的个数
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2"}) print(r.hlen("hash-name1")) #显示如下: 2 Process finished with exit code 0
- hkeys(name)
# 获取name对应的hash中所有的key的值
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2"}) print(r.hkeys("hash-name1")) #显示如下: [b'k2', b'k1'] Process finished with exit code 0
- hvals(name)
# 获取name对应的hash中所有的value的值
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2"}) print(r.hvals("hash-name1")) #显示如下: [b'v2', b'v1'] Process finished with exit code 0
- hexists(name, key)
# 检查name对应的hash是否存在当前传入的key
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2"}) tet1 = r.hexists("hash-name1","k1") print(tet1) tet2 = r.hexists("hash-name1","k3") print(tet2) #显示如下: True False Process finished with exit code 0
- hdel(name,*keys)
将name对应的hash中指定key的键值对删除
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2"}) print(r.hgetall("hash-name1")) r.hdel("hash-name1","k1") print(r.hgetall("hash-name1")) #显示如下: {b'k2': b'v2', b'k1': b'v1'} {b'k2': b'v2'} Process finished with exit code 0
- hincrby(name, key, amount=1)
# 自增name对应的hash中的指定key的值,不存在则创建key=amount
# 参数:
# name,redis中的name
# key, hash对应的key
# amount,自增数(整数)
- hincrbyfloat(name, key, amount=1.0)
# 自增name对应的hash中的指定key的值,不存在则创建key=amount
# 参数:
# name,redis中的name
# key, hash对应的key
# amount,自增数(浮点数)
# 自增name对应的hash中的指定key的值,不存在则创建key=amount
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.hset("hash-name","k1","v1") r.hmset("hash-name1",{"k1":"v1","k2":"v2","k3":20}) r.hincrby("hash-name1",key="k3",amount=1) print(r.hgetall("hash-name1")) r.hincrby("hash-name1",key="k5",amount=1) #k5默认不存在 会自动创建 print(r.hgetall("hash-name1")) #显示如下: {b'k1': b'v1', b'k2': b'v2', b'k4': b'2', b'k3': b'21'} {b'k1': b'v1', b'k5': b'1', b'k2': b'v2', b'k4': b'2', b'k3': b'21'} Process finished with exit code 0
- hscan(name, cursor=0, match=None, count=None)
# 增量式迭代获取,对于数据大的数据非常有用,hscan可以实现分片的获取数据,并非一次性将数据全部获取完,从而放置内存被撑爆
# 参数:
# name,redis的name
# cursor,游标(基于游标分批取获取数据)
# match,匹配指定key,默认None 表示所有的key
# count,每次分片最少获取个数,默认None表示采用Redis的默认分片个数
# 如:
# 第一次:cursor1, data1 = r.hscan('xx', cursor=0, match=None, count=None)
# 第二次:cursor2, data1 = r.hscan('xx', cursor=cursor1, match=None, count=None)
# ...
# 直到返回值cursor的值为0时,表示数据已经通过分片获取完毕
- hscan_iter(name, match=None, count=None)
# 利用yield封装hscan创建生成器,实现分批去redis中获取数据
# 参数:
# match,匹配指定key,默认None 表示所有的key
# count,每次分片最少获取个数,默认None表示采用Redis的默认分片个数
# 如:
# for item in r.hscan_iter('xx'):
# print item
![](https://images2015.cnblogs.com/blog/933015/201607/933015-20160721104400169-2085692624.png)
- lpush(name,values)
# 在name对应的list中添加元素,每个新的元素都添加到列表的最左边
# 如:
# r.lpush('oo', 11,22,33)
# 保存顺序为: 33,22,11
# 扩展:
# rpush(name, values) 表示从右向左操作
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.lpush("list-name","v1","v2","v3")
- lpushx(name,value)
# 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最左边
# 更多:
# rpushx(name, value) 表示从右向左操作
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.lpush("list-name","v1","v2","v3") r.lpushx("list-name","v4")
- llen(name)
# name对应的list元素的个数
r.lpush("list-name1","v1","v2","v3") r.lpushx("list-name1","v4") ret = r.llen("list-name1") print(ret) #显示 4
- linsert(name, where, refvalue, value))
# 在name对应的列表的某一个值前或后插入一个新值
# 参数:
# name,redis的name
# where,BEFORE或AFTER
# refvalue,标杆值,即:在它前后插入数据
# value,要插入的数据
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.lpush("list-name1","v1","v2","v3") #r.lpushx("list-name1","v4") r.linsert("list-name1","BEFORE","v2","insert-v") ret = r.llen("list-name1") print(ret) ## 5
- r.lset(name, index, value)
# 对name对应的list中的某一个索引位置重新赋值
# 参数:
# name,redis的name
# index,list的索引位置
# value,要设置的值
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.lpush("list-name1","v1","v2","v3") #r.lpushx("list-name1","v4") # r.linsert("list-name1","BEFORE","v2","insert-v") r.lset("list-name1",0,"index-v")
- r.lrem(name, value, num)
# 在name对应的list中删除指定的值
# 参数:
# name,redis的name
# value,要删除的值
# num, num=0,删除列表中所有的指定值;
# num=2,从前到后,删除2个;
# num=-2,从后向前,删除2个
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.lpush("list-name1","v1","v2","v3") #r.lpushx("list-name1","v4") # r.linsert("list-name1","BEFORE","v2","insert-v") r.lrem("list-name",value="v3")
- lpop(name)
# 在name对应的列表的左侧获取第一个元素并在列表中移除,返回值则是第一个元素
# 更多:
# rpop(name) 表示从右向左操作
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.lpush("list-name1","v1","v2","v3") #r.lpushx("list-name1","v4") # r.linsert("list-name1","BEFORE","v2","insert-v") print(r.lpop("list-name1")) #显示如下: b'v4' Process finished with exit code 0
- lindex(name, index)
#在name对应的列表中根据索引获取列表元素
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.lpush("list-name1","v1","v2","v3") #r.lpushx("list-name1","v4") # r.linsert("list-name1","BEFORE","v2","insert-v") print(r.lindex("list-name1",0)) ###### b'v3' Process finished with exit code 0
- lrange(name, start, end)
# 在name对应的列表分片获取数据
# 参数:
# name,redis的name
# start,索引的起始位置
# end,索引结束位置
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.lpush("list-name1","v1","v2","v3") #r.lpushx("list-name1","v4") # r.linsert("list-name1","BEFORE","v2","insert-v") print(r.lrange("list-name1",0,-1)) ### [b'v3', b'insert-v', b'v2', b'v1'] Process finished with exit code 0
- ltrim(name, start, end)
# 在name对应的列表中移除没有在start-end索引之间的值
# 参数:
# name,redis的name
# start,索引的起始位置
# end,索引结束位置
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) print(r.lrange("list-name1",0,-1)) r.ltrim("list-name1",0,2) print(r.lrange("list-name1",0,-1)) #显示如下: [b'v3', b'insert-v', b'v2', b'v1'] [b'v3', b'insert-v', b'v2'] Process finished with exit code 0
- rpoplpush(src, dst)
# 从一个列表取出最右边的元素,同时将其添加至另一个列表的最左边
# 参数:
# src,要取数据的列表的name
# dst,要添加数据的列表的name
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) print(r.lrange("list-name1",0,-1)) r.rpoplpush("list-name1","list-new") print(r.lrange("list-new",0,-1)) #显示 [b'v3', b'insert-v', b'v2'] [b'v2'] Process finished with exit code 0
- blpop(keys, timeout)
将多个列表排列,按照从左到右去pop对应列表的元素
# 参数:
# keys,redis的name的集合
# timeout,超时时间,当元素所有列表的元素获取完之后,阻塞等待列表内有数据的时间(秒), 0 表示永远阻塞
# 更多:
# r.brpop(keys, timeout),从右向左获取数据
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.lpush("list-name2","v1","v2","v3") r.lpushx("list-name2","v4") r.linsert("list-name2","BEFORE","v2","insert-v") r.rpoplpush("list-name2","list-new1") keys = ['list-name2','list-new1'] print(r.lrange("list-new1",0,-1)) print(r.lrange("list-name2",0,-1)) print(r.blpop(keys)) print(r.lrange("list-new1",0,-1)) print(r.lrange("list-name2",0,-1)) #第一次执行显示如下: [b'v1'] [b'v4', b'v3', b'insert-v', b'v2'] (b'list-name2', b'v4') #v4为获取的值 [b'v1'] [b'v3', b'insert-v', b'v2'] ###########第二次需要注释掉前面生成的代码: import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) # r.lpush("list-name2","v1","v2","v3") # r.lpushx("list-name2","v4") # r.linsert("list-name2","BEFORE","v2","insert-v") # r.rpoplpush("list-name2","list-new1") keys = ['list-name2','list-new1'] print(r.lrange("list-new1",0,-1)) print(r.lrange("list-name2",0,-1)) print(r.blpop(keys)) print(r.lrange("list-new1",0,-1)) print(r.lrange("list-name2",0,-1)) #####第二次执行如下: [b'v1'] [b'v3', b'insert-v', b'v2'] (b'list-name2', b'v3') [b'v1'] [b'insert-v', b'v2'] #####第三次继续执行 [b'v1'] [b'insert-v', b'v2'] (b'list-name2', b'insert-v') [b'v1'] [b'v2'] #####四 [b'v1'] [b'v2'] (b'list-name2', b'v2') [b'v1'] [] #####五 [b'v1'] [] (b'list-new1', b'v1') [] [] ####六 [] [] ------》已经取完现在处于阻塞状态
- brpoplpush(src, dst, timeout=0)
# 从一个列表的右侧移除一个元素并将其添加到另一个列表的左侧
# 参数:
# src,取出并要移除元素的列表对应的name
# dst,要插入元素的列表对应的name
# timeout,当src对应的列表中没有数据时,阻塞等待其有数据的超时时间(秒),0 表示永远阻塞
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.lpush("list-name3","v1","v2","v3") print(r.lrange("list-name3",0,-1)) r.brpoplpush("list-name3","list-name4") print(r.lrange("list-name4",0,-1)) #显示 [b'v3', b'v2', b'v1'] [b'v1'] Process finished with exit code 0
- 自定义增量迭代
# 由于redis类库中没有提供对列表元素的增量迭代,如果想要循环name对应的列表的所有元素,那么就需要:
# 1、获取name对应的所有列表
# 2、循环列表
# 但是,如果列表非常大,那么就有可能在第一步时就将程序的内容撑爆,所有有必要自定义一个增量迭代的功能:
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) #r.lpush("list-name3","v1","v2","v3") print(r.lrange("list-name3",0,-1)) def list_iter(name): """ 自定义redis列表增量迭代 :param name: redis中的name,即:迭代name对应的列表 :return: yield 返回 列表元素 """ list_count = r.llen(name) for index in range(list_count): yield r.lindex(name, index) # 使用 for item in list_iter('list-name3'): print(item) #显示如下: [b'v3', b'v2'] b'v3' b'v2' Process finished with exit code 0
Set操作,Set集合就是不允许重复的列表
- sadd(name,values)
# name对应的集合中添加元素
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1")
- scard(name)
#获取name对应的集合中元素个数
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) print(r.scard("set-name")) #显示 1
- sdiff(keys, *args)
在第一个name对应的集合中且不在其他name对应的集合的元素集合
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.scard("set-name")) r.sadd("set-name1","v1") r.sadd("set-name1","v2") r.sadd("set-name1","v5") r.sadd("set-name1","v6") print(r.scard("set-name1")) keys = ["set-name","set-name1"] ret = r.sdiff(keys) print(ret) #显示如下: 4 4 {b'v3', b'v4'} Process finished with exit code 0
- sdiffstore(dest, keys, *args)
# 获取第一个name对应的集合中且不在其他name对应的集合,再将其新加入到dest对应的集合中
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.scard("set-name")) r.sadd("set-name1","v1") r.sadd("set-name1","v2") r.sadd("set-name1","v5") r.sadd("set-name1","v6") print(r.scard("set-name1")) keys = ["set-name","set-name1"] r.sdiffstore("set-name2",keys) print(r.scard("set-name2")) #显示: 4 4 2
- sinter(keys, *args)
# 获取多一个name对应集合的并集
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.scard("set-name")) r.sadd("set-name1","v1") r.sadd("set-name1","v2") r.sadd("set-name1","v5") r.sadd("set-name1","v6") print(r.scard("set-name1")) r.sadd("set-name3","v1") r.sadd("set-name3","v2") r.sadd("set-name3","v7") r.sadd("set-name3","v8") keys = ["set-name","set-name1","set-name3"] print(r.sinter(keys)) #显示如下: 4 4 {b'v1', b'v2'} Process finished with exit code 0
- sinterstore(dest, keys, *args)
# 获取多一个name对应集合的交集,再讲其加入到dest对应的集合中
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.scard("set-name")) r.sadd("set-name1","v1") r.sadd("set-name1","v2") r.sadd("set-name1","v5") r.sadd("set-name1","v6") print(r.scard("set-name1")) r.sadd("set-name3","v1") r.sadd("set-name3","v2") r.sadd("set-name3","v7") r.sadd("set-name3","v8") keys = ["set-name","set-name1","set-name3"] r.sinterstore("set-name4",keys)
#显示
{b'v2', b'v1'}
Process finished with exit code 0
- sismember(name, value)
# 检查value是否是name对应的集合的成员
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.sismember("set-name","v1")) print(r.sismember("set-name","v7")) #显示如下: True False Process finished with exit code 0
- smembers(name)
# 获取name对应的集合的所有成员
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.smembers("set-name")) #显示 {b'v1', b'v3', b'v4', b'v2'} Process finished with exit code 0
- smove(src, dst, value)
# 将某个成员从一个集合中移动到另外一个集合
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name5","v1") r.sadd("set-name5","v2") r.sadd("set-name5","v3") r.sadd("set-name5","v4") print(r.smembers("set-name5")) r.smove("set-name5","set-name6","v1") print(r.smembers("set-name5")) print(r.smembers("set-name6")) #显示: {b'v2', b'v1', b'v4', b'v3'} {b'v2', b'v4', b'v3'} {b'v1'} Process finished with exit code 0
- spop(name)
# 从集合的右侧(尾部)移除一个成员,并将其返回
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name5","v1") r.sadd("set-name5","v2") r.sadd("set-name5","v3") r.sadd("set-name5","v4") print(r.smembers("set-name5")) print(r.spop("set-name5")) print(r.smembers("set-name5")) ##显示 {b'v4', b'v3', b'v1', b'v2'} b'v2' {b'v4', b'v3', b'v1'} Process finished with exit code 0
- srandmember(name, numbers)
# 从name对应的集合中随机获取 numbers 个元素
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name5","v1") r.sadd("set-name5","v2") r.sadd("set-name5","v3") r.sadd("set-name5","v4") print(r.smembers("set-name5")) print(r.srandmember("set-name5",2)) ##显示 {b'v2', b'v3', b'v4', b'v1'} [b'v1', b'v3'] Process finished with exit code 0
- srem(name, values)
# 在name对应的集合中删除某些值
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name5","v1") r.sadd("set-name5","v2") r.sadd("set-name5","v3") r.sadd("set-name5","v4") print(r.smembers("set-name5")) r.srem("set-name5","v1","v2") print(r.smembers("set-name5")) ##显示 {b'v1', b'v2', b'v4', b'v3'} {b'v4', b'v3'} Process finished with exit code 0
- sunion(keys, *args)
# 获取多一个name对应的集合的并集
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.scard("set-name")) r.sadd("set-name1","v1") r.sadd("set-name1","v2") r.sadd("set-name1","v5") r.sadd("set-name1","v6") print(r.scard("set-name1")) r.sadd("set-name3","v1") r.sadd("set-name3","v2") r.sadd("set-name3","v7") r.sadd("set-name3","v8") keys = ["set-name","set-name1","set-name3"] print(r.sunion(keys)) ###显示 4 4 {b'v3', b'v7', b'v5', b'v1', b'v6', b'v8', b'v2', b'v4'} Process finished with exit code 0
- sunionstore(dest,keys, *args)
# 获取多个name对应的集合的并集,并将结果保存到dest对应的集合中
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.sadd("set-name","v1") r.sadd("set-name","v2") r.sadd("set-name","v3") r.sadd("set-name","v4") print(r.scard("set-name")) r.sadd("set-name1","v1") r.sadd("set-name1","v2") r.sadd("set-name1","v5") r.sadd("set-name1","v6") print(r.scard("set-name1")) r.sadd("set-name3","v1") r.sadd("set-name3","v2") r.sadd("set-name3","v7") r.sadd("set-name3","v8") keys = ["set-name","set-name1","set-name3"] r.sunionstore("set-name6",keys) print(r.smembers("set-name6")) #显示如下 4 4 {b'v3', b'v8', b'v4', b'v2', b'v7', b'v6', b'v1', b'v5'} Process finished with exit code 0
- sscan(name, cursor=0, match=None, count=None)
- sscan_iter(name, match=None, count=None)
# 同字符串的操作,用于增量迭代分批获取元素,避免内存消耗太大
有序集合,在集合的基础上,为每元素排序;元素的排序需要根据另外一个值来进行比较,所以,对于有序集合,每一个元素有两个值,即:值和分数,分数专门用来做排序。
- zadd(name, *args, **kwargs)
# 在name对应的有序集合中添加元素
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset', 'n1', 1, 'n2', 2) r.zadd('name-zset', n1=11, n2=22) #
- zcard(name)
# 获取name对应的有序集合元素的数量
r.zadd('name-zset', 'n1', 1, 'n2', 2) # r.zadd('zz', n1=11, n2=22) ret = r.zcard("name-zset") print(ret) ##显示 2 Process finished with exit code 0
- zcount(name, min, max)
# 获取name对应的有序集合中分数 在 [min,max] 之间的个数
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) # r.zadd('zz', n1=11, n2=22) ret = r.zcount("name-zset",1,4) print(ret) #显示 4 Process finished with exit code 0
- zincrby(name, value, amount)
# 自增name对应的有序集合的 name 对应的分数
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) # r.zadd('zz', n1=11, n2=22) r.zincrby("name-zset","n1")
- r.zrange( name, start, end, desc=False, withscores=False, score_cast_func=float)
# 按照索引范围获取name对应的有序集合的元素
# 参数:
# name,redis的name
# start,有序集合索引起始位置(非分数)
# end,有序集合索引结束位置(非分数)
# desc,排序规则,默认按照分数从小到大排序
# withscores,是否获取元素的分数,默认只获取元素的值
# score_cast_func,对分数进行数据转换的函数
# 更多:
# 从大到小排序
# zrevrange(name, start, end, withscores=False, score_cast_func=float)
# 按照分数范围获取name对应的有序集合的元素
# zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=float)
# 从大到小排序
# zrevrangebyscore(name, max, min, start=None, num=None, withscores=False, score_cast_func=float)
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) # r.zadd('zz', n1=11, n2=22) # r.zincrby("name-zset","n1") print(r.zrange('name-zset',0,3,)) #显示 [b'n1', b'n2', b'n3', b'n4'] Process finished with exit code 0
- zrank(name, value)
# 获取某个值在 name对应的有序集合中的排行(从 0 开始)
# 更多:
# zrevrank(name, value),从大到小排序
r.zadd('name-zset', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) # r.zadd('zz', n1=11, n2=22) # r.zincrby("name-zset","n1") # print(r.zrange('name-zset',0,3,)) print(r.zrank("name-zset","n2")) ##显示 1
- zrangebylex(name, min, max, start=None, num=None)
# 当有序集合的所有成员都具有相同的分值时,有序集合的元素会根据成员的 值 (lexicographical ordering)来进行排序,而这个命令则可以返回给定的有序集合键 key 中, 元素的值介于 min 和 max 之间的成员
# 对集合中的每个成员进行逐个字节的对比(byte-by-byte compare), 并按照从低到高的顺序, 返回排序后的集合成员。 如果两个字符串有一部分内容是相同的话, 那么命令会认为较长的字符串比较短的字符串要大
# 参数:
# name,redis的name
# min,左区间(值)。 + 表示正无限; - 表示负无限; ( 表示开区间; [ 则表示闭区间
# min,右区间(值)
# start,对结果进行分片处理,索引位置
# num,对结果进行分片处理,索引后面的num个元素
# 更多:
# 从大到小排序
# zrevrangebylex(name, max, min, start=None, num=None)
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset', 'aa', 0, 'ba', 0, 'ca', 0, 'da', 0, 'ea', 0, 'fa', 0, 'ga',0) print(r.zrangebylex('name-zset', "-", "[ca")) ##显示 [b'aa', b'ba', b'ca'] Process finished with exit code 0
- zrem(name, values)
# 删除name对应的有序集合中值是values的成员
import redis
pool = redis.ConnectionPool(host='192.168.1.103',port=6379)
r = redis.Redis(connection_pool=pool)
r.zadd('name-zset1', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4)
print(r.zrange("name-zset1",0,-1))
r.zrem("name-zset1","n1","n3")
print(r.zrange("name-zset1",0,-1))
###显示如下
[b'n1', b'n2', b'n3', b'n4']
[b'n2', b'n4']
Process finished with exit code 0
- zremrangebyrank(name, min, max)
# 根据排行范围删除(min&&max并非分数值)
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset1', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) print(r.zrange("name-zset1",0,-1)) r.zremrangebyrank("name-zset1",1,2) print(r.zrange("name-zset1",0,-1)) ## [b'n1', b'n2', b'n3', b'n4'] [b'n1', b'n4'] Process finished with exit code 0
- zremrangebyscore(name, min, max)
# 根据分数范围删除
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset1', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) print(r.zrange("name-zset1",0,-1)) r.zremrangebyscore("name-zset1",1,2) print(r.zrange("name-zset1",0,-1)) ##显示 [b'n1', b'n2', b'n3', b'n4'] [b'n3', b'n4'] Process finished with exit code 0
- zremrangebylex(name, min, max)
# 根据值返回删除
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd("name-zset3",'aaaa', 0 ,'b', 0 ,'c', 0 ,'d',0 ,'e',0) r.zadd("name-zset3",'foo', 0, 'zap', 0, 'zip', 0, 'ALPHA', 0, 'alpha',0) print(r.zrange("name-zset3",0,-1)) r.zremrangebylex("name-zset3","[alpha","[omega") print(r.zrange("name-zset3",0,-1)) #显示如下 [b'ALPHA', b'aaaa', b'alpha', b'b', b'c', b'd', b'e', b'foo', b'zap', b'zip'] [b'ALPHA', b'aaaa', b'zap', b'zip'] Process finished with exit code 0
- zscore(name, value)
# 获取name对应有序集合中 value 对应的分数
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset1', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) print(r.zscore("name-zset1","n3")) # 显示如下: 3.0 Process finished with exit code 0
- zinterstore(dest, keys, aggregate=None)
# 获取两个有序集合的交集,如果遇到相同值不同分数,则按照aggregate进行操作
# aggregate的值为: SUM MIN MAX
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset1', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset2', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) keys = ["name-zset1","name-zset2"] r.zinterstore("name-zset3",keys) print(r.zrange("name-zset3",0,-1)) ##显示 [b'n3', b'n4'] Process finished with exit code 0
- zunionstore(dest, keys, aggregate=None)
# 获取两个有序集合的并集,如果遇到相同值不同分数,则按照aggregate进行操作
# aggregate的值为: SUM MIN MAX
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) keys = ["name-zset10","name-zset20"] r.zunionstore("name-zset30",keys) print(r.zrange("name-zset30",0,-1)) #显示如下: [b'n1', b'z1', b'n2', b'z2', b'n3', b'n4'] Process finished with exit code 0
- zscan(name, cursor=0, match=None, count=None, score_cast_func=float)
- zscan_iter(name, match=None, count=None,score_cast_func=float)
# 同字符串相似,相较于字符串新增score_cast_func,用来对分数进行操作
其他常用操作
delete(*names)
# 根据名字删除redis中的任意数据类型
##以有序集合为例 import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) r.delete("name-zset20") print(r.zrange("name-zset20",0,-1)) print(r.zrange("name-zset10",0,-1)) ##显示 [] #---》已经清空 [b'n1', b'n2', b'n3', b'n4'] Process finished with exit code 0
exists(name)
# 检测redis的name是否存在
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) r.delete("name-zset20") print(r.exists("name-zset20")) print(r.exists("name-zset10")) #显示 False True Process finished with exit code 0
keys(pattern='*')
# 根据模型获取redis的name
# 更多:
# KEYS * 匹配数据库中所有 key 。
# KEYS h?llo 匹配 hello , hallo 和 hxllo 等。
# KEYS h*llo 匹配 hllo 和 heeeeello 等。
# KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) r.delete("name-zset20") print(r.keys(pattern='*zset*')) ##显示 [b'name-zset1', b'name-zset5', b'name-zset3', b'name-zset', b'name-zset4', b'name-zset10', b'name-zset30', b'name-zset2', b'name-zset6'] Process finished with exit code 0
expire(name ,time)
# 为某个redis的某个name设置超时时间
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) r.expire("name-zset20",30) #
rename(src, dst)
# 对redis的name重命名为
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) r.rename("name-zset20","name-zset40") print(r.zrange("name-zset40",0,-1)) #显示 [b'z1', b'z2', b'n3', b'n4'] Process finished with exit code 0
move(name, db))
# 将redis的某个值移动到指定的db下
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) r.rename("name-zset20","name-zset40") print(r.zrange("name-zset40",0,-1)) r.move("name-zset40",2) ##从默认库下移动到编号为2的库下
randomkey()
# 随机获取一个redis的name(不删除)
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) # r.rename("name-zset20","name-zset40") # print(r.zrange("name-zset40",0,-1)) print(r.randomkey()) ##显示 b'set-name2' #随机获取的值,每次不一定相同 Process finished with exit code 0
type(name)
# 获取name对应值的类型
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) r.zadd('name-zset10', 'n1', 1, 'n2', 2,'n3', 3,'n4', 4) r.zadd('name-zset20', 'z1', 1, 'z2', 2,'n3', 3,'n4', 4) # r.rename("name-zset20","name-zset40") # print(r.zrange("name-zset40",0,-1)) print(r.type("name-zset10")) ## b'zset' Process finished with exit code 0
scan(cursor=0, match=None, count=None)
scan_iter(match=None, count=None)
# 同字符串操作,用于增量迭代获取key
管道
redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。
import redis pool = redis.ConnectionPool(host='192.168.1.103',port=6379) r = redis.Redis(connection_pool=pool) # pipe = r.pipeline(transaction=False) pipe = r.pipeline(transaction=True) r.set('name', 'zhaowencheng-hell0') r.set('age', '26') print(r.get("name")) print(r.get("age")) pipe.execute() ## b'zhaowencheng-hell0' b'26' Process finished with exit code 0