🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#0、Redis介绍 Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。 总之,redis比memcache多了存储在本地,支持数据结构方法。以及一些其它。属缓存又属数据库。 **redis安装:** ~~~ yum install -y redis chkconfig redis on service redis start ~~~ #1、Redis-Py 安装 `pip install redis` > redis.StrictRedis : 这是redis-py的底层实现 > Redis.Redis : 这是高级方法,引用基类StrictRedis #2、连接类型 redis数据库有两种连接类型,一种是传统连接,一种是通过连接池的方法进行连接。 这两种方法返回的对象的操作方法都是一样的。 ##2.1、普通连接 ~~~ from redis.client import Redis client = Redis() #这里传参数信息 ~~~ ##2.2、连接池(安全线程连接池连接) ~~~ from redis.client import Redis client = Redis(connection_pool=BlockingConnectionPool()) BlockingConnectionPool max_connections=10 #调整池内复用连接数 timeout :调整超时时间 ~~~ #3、操作方法 主要操作方法了是要学会redis的类型,如STR、HASH、LIST、SET、SORTSET。这是固有方法。 对于方法的话一般通用原则就是增册改查方法。对应redis本身有过期时间TTL这个概念会提供专用方法设计。 比如字符串在Redis里有如下方法:每个都具有特殊的意义,在redis-py当中了也是同样 > SET > SETNX > SETEX > SETRANGE > MSET > MSETNX > APPEND > GET > MGET > GETRANGE > GETSET > STRLEN > DECR > DECRBY > INCR > INCRBY > SETBIT > GETBIT #4、STR字符串 Redis 字符串其实类似python的字典,就是一个键值对,值为字符串。 key:value形式,就是常用方法,增册改查。册要利用redis 的key方法,而不是字符串的方法。 ##A、简单进行增和查 set get set mset append get mget 等等 set 原型: `set(self, name, value, ex=None, px=None, nx=False, xx=False)` 接收参数key value ex:设置超时时间,单秒秒 seconds. px:设置超时时间,单位毫秒 milliseconds. ~~~ In [22]: client.set('user','zwhset') Out[22]: True In [23]: client.get('user') #获取一个key的值 Out[23]: 'zwhset' ~~~ ##B、添加多个值 mset mget 以字典key:value方式添加到redis里 mset原型: ~~~ mset(self, *args, **kwargs) method of redis.client.Redis instance Sets key/values based on a mapping. Mapping can be supplied as a single dictionary argument or as kwargs. ~~~ ~~~ In [26]: info = {'z1':1,'z2':2,'z3':3} In [27]: client.mset(\*\*info) Out[27]: True In [30]: client.mget('z1','z2','z3') Out[30]: ['1', '2', '3'] ~~~ ##C、追加值到末尾 ~~~ append(self, key, value) method of redis.client.Redis instance Appends the string ``value`` to the value at ``key``. If ``key`` doesn't already exist, create it with a value of ``value``. Returns the new length of the value at ``key``. ~~~ 如果值不存在,新建值,相当于client.set,如果值存在添加到字符串末尾,相当于字符串 S1 + S2方法 ~~~ In [32]: client.exists('china') #测试KEY存在不存在 Out[32]: False #不存在china的KEY In [33]: client.append('china','hunan') #追加,但无KEY,相当于SET方法 Out[33]: 5L In [34]: client.append('china','.xiangtan') #已经有值了,相当于S1+S2 Out[34]: 14L In [35]: client.get('china') #查看结果 Out[35]: 'hunan.xiangtan' ~~~ ##D、获取部份字符串,分片 getrange 原型: ~~~ getrange(self, key, start, end) method of redis.client.Redis instance Returns the substring of the string value stored at ``key``, determined by the offsets ``start`` and ``end`` (both are inclusive) (END) ~~~ ~~~ In [37]: client.getrange('china',0,10) #获取0,10的分片,不会的重学python Out[37]: 'hunan.xiang' In [38]: client.getrange('china',0,4) \#0-4 Out[38]: 'hunan' In [39]: client.getrange('china',4,-2) #引入负值,负值是从后往前数的 Out[39]: 'n.xiangta' ~~~ ##E、对KEY的值进行+1,相当于 原型: ~~~ incr(self, name, amount=1) method of redis.client.Redis instance Increments the value of ``key`` by ``amount``. If no key exists, the value will be initialized as ``amount`` ~~~ 对key的值进行+1操作,默认,否则加amout数 如果要用减1则用DECR ~~~ In [41]: client.set('sex',1) Out[41]: True In [42]: client.incr('sex') Out[42]: 2 In [43]: client.incr('sex') Out[43]: 3 In [44]: client.incr('sex',2) Out[44]: 5 In [45]: client.incr('sex',4) Out[45]: 9 ~~~ ##F、当Key不存在时添加Key ~~~ setnx(self, name, value) method of redis.client.Redis instance Set the value of key ``name`` to ``value`` if key doesn't exist ~~~ ~~~ In [4]: client.get('age') #KEY存在 Out[4]: '16' In [5]: client.setnx('age',100) #添加为False Out[5]: False In [6]: client.get('age2000')#KEY不存在 In [7]: client.setnx('age2000',100)#添加成功,返回True Out[7]: True ~~~ ##E、设置key的值并返回老值 getset ~~~ getset(self, name, value) method of redis.client.Redis instance Sets the value at key ``name`` to ``value`` and returns the old value at key ``name`` atomically. ~~~ ~~~ In [3]: client.get('age') #老值16 Out[3]: '16' In [5]: client.getset('age',20) #设置新值,并返回老值 Out[5]: '16' In [6]: client.get('age') #新值20 Out[6]: '20' ~~~ #5、HASH 字典 redis的hash类型对应的是python的字典类型 python一个字典对象 website = { 'google':'http://www.google.com', 'baidu':'http://www.baidu.com' } ##A、添加值,注意会覆盖,如果不想可以用NX方法 > HSET HMSET HSETNX ~~~ hset(self, name, key, value) method of redis.client.Redis instance Set ``key`` to ``value`` within hash ``name`` Returns 1 if HSET created a new field, otherwise 0 添加一个叫name的字典,key value对应,如果设置了一个新的字段返回1,否则返回0 hmset(self, name, mapping) method of redis.client.Redis instance Set key to value within hash ``name`` for each corresponding key and value from the ``mapping`` dict. 批量添加key value 类我们python的 dict.update()方法,合并KEY name:字典名,mapping给定的字典 hsetnx(self, name, key, value) method of redis.client.Redis instance Set ``key`` to ``value`` within hash ``name`` if ``key`` does not exist. Returns 1 if HSETNX created a field, otherwise 0. 如果key不存在添加进去,存在则不加,创建了KEY返回1,否则返回0 ~~~ **HSET** ~~~ In [21]: client.hset('website','google','http://www.google.com') Out[21]: 1L # 添加一个新的字典,并且google的值是新添加的字典 In [22]: client.hset('website','google','http://www.google.com') Out[22]: 0L # 这里不是新添加key,所以返回0 In [23]: client.hset('website','google','http://www.google.com/nc') Out[23]: 0L #同理,替换key的值,返回0 ~~~ **HMSET** ~~~ In [25]: info = { ...: 'baidu':'www.baidu.com', ...: 'weibo':'www.weibo.com',} #设定一下字典 In [26]: client.hgetall('website') #只有一个google的key Out[26]: {'google': 'http://www.google.com/nc'} In [27]: client.hmset('website',info) #传入字典,合并操作 Out[27]: True In [28]: client.hgetall('website') # 值已经合并完成 Out[28]: {'baidu': 'www.baidu.com', 'google': 'http://www.google.com/nc', 'weibo': 'www.weibo.com'} ~~~ **HSETNX** In [29]: client.hget('website','weibo') #字典中有KEY Out[29]: 'www.weibo.com' In [30]: client.hsetnx('website','weibo','www.163.com') #添加不成功返回0 Out[30]: 0L In [31]: client.hget('website','weibo') #值未发生变化 Out[31]: 'www.weibo.com' In [32]: client.hsetnx('website','163','www.163.com')#添加新KEY Out[32]: 1L In [33]: client.hget('website','163') 成功 Out[33]: 'www.163.com' ##B、查值 > HGET 获取KEY 等同于dict[key] > HGETALL 获取字典 等同于dict > HKEYS 获取所有Keys 等同于dict.keys() > HMGET 获取多个KEY  > HVALS 获取所有值 返回列表 ~~~ hget(self, name, key) method of redis.client.Redis instance Return the value of ``key`` within the hash ``name`` 返回KEY的值 hgetall(self, name) method of redis.client.Redis instance Return a Python dict of the hash's name/value pairs 返回name字典对象 hkeys(self, name) method of redis.client.Redis instance Return the list of keys within hash ``name`` 返回所有KEY,列表 hmget(self, name, keys, *args) method of redis.client.Redis instance Returns a list of values ordered identically to ``keys`` 返回所有给定的KEYS hvals(self, name) method of redis.client.Redis instance Return the list of values within hash ``name`` 返回所有VALUE 列表 ~~~ ~~~ In [41]: client.hget('website','163') Out[41]: 'www.163.com' In [43]: client.hgetall('website') Out[43]: {'163': 'www.163.com', 'baidu': 'www.baidu.com', 'google': 'http://www.google.com/nc', 'weibo': 'www.weibo.com'} In [44]: client.hkeys('website') Out[44]: ['google', 'baidu', 'weibo', '163'] In [46]: client.hvals('website') Out[46]: ['http://www.google.com/nc', 'www.baidu.com', 'www.weibo.com', 'www.163.com'] In [47]: client.hmget('website',['google','163','test']) Out[47]: ['http://www.google.com/nc', 'www.163.com', None] ~~~ 同样也存在加1的方法 **嵌套字典会存为一个字符串,这个是需要注意的** ~~~ In [48]: info = { ...: 'sohu':{ ...: 'web':1, ...: 'test':2 ...: }} In [49]: In [49]: client.hmset('website',info) Out[49]: True In [50]: client.hgetall('website') Out[50]: {'163': 'www.163.com', 'baidu': 'www.baidu.com', 'google': 'http://www.google.com/nc', 'sohu': "{'test': 2, 'web': 1}", 'weibo': 'www.weibo.com'} In [51]: client.hget('website','sohu') Out[51]: "{'test': 2, 'web': 1}" ~~~ #6、LIST 列表 LIST相当于python的列表,提供相同的方法,下标(索引)取值,提供阻塞方法,所以可以用于消息队列这样的场景。 > LINDEX 索引取值 list[index] > LINSERT 索引写入值 list.insert() > LLEN 列表长度 len(list) > LPOP 列表删除并拿到值 list.pop() > LPUSH 将值写入表头 list.insert(0,value) > LPUSHX 值写入表头,并且name为一个list nx方法 > LRANGE 区间取值 list[i:j] > LREM 移除列表中值等于cout的元素 > LSET 列表设置值 list[index] = value > LTRIM 只保留区间元素,其它删除 list = list[i:j] > RPOP 移除并返回列表尾元素 > RPUSH 将值插入表尾 > RPUSHX 列表不存在时不插入,存在时插入 ##A、写值 **LPUSH LPUSHX LSET RPUSH RPUSHX LINSERT** 原型: ~~~ lpush(self, name, *values) method of redis.client.Redis instance Push ``values`` onto the head of the list ``name`` 将一个或多个值value插入到列表key的表头。注意*values是位置传参 lpushx(self, name, value) method of redis.client.Redis instance Push ``value`` onto the head of the list ``name`` if ``name`` exists 当name存在时进行表头元素写入,当然不存在就啥也不做。与nx方法相反哟。 lset(self, name, index, value) method of redis.client.Redis instance Set ``position`` of list ``name`` to ``value`` 修改name[index]的值为value,超范围会给异常 rpush(self, name, *values) method of redis.client.Redis instance Push ``values`` onto the tail of the list ``name`` 往表尾写入元素,注意values是人位置传参 rpushx(self, name, value) method of redis.client.Redis instance Push ``value`` onto the tail of the list ``name`` if ``name`` exists 当name存在时往表尾写入元素,不存在啥也不干 linsert(self, name, where, refvalue, value) method of redis.client.Redis instance Insert ``value`` in list ``name`` either immediately before or after [``where``] ``refvalue`` 将值value插入到refvalue之前或之后 where为before after Returns the new length of the list on success or -1 if ``refvalue`` is not in the list. ~~~ ~~~ In [19]: client.lpush('names','zhangsan') #左插 Out[19]: 1L In [20]: client.lpush('names','lisi','wangwu') Out[20]: 3L In [21]: client.lrange('names',0,-1) #取所有值 Out[21]: ['wangwu', 'lisi', 'zhangsan'] In [22]: client.lpushx('names','zhaoliu') #存在则左插 Out[22]: 4 In [23]: client.lrange('names',0,-1) Out[23]: ['zhaoliu', 'wangwu', 'lisi', 'zhangsan'] In [24]: client.lpushx('namesxxx','zhaoliu') # 不存在不插 Out[24]: 0 In [25]: client.lrange('names',0,-1) Out[25]: ['zhaoliu', 'wangwu', 'lisi', 'zhangsan'] In [26]: client.lset('names',0,'wangba') Out[26]: True In [27]: client.lrange('names',0,-1) Out[27]: ['wangba', 'wangwu', 'lisi', 'zhangsan'] In [29]: client.lrange('names',0,-1) Out[29]: ['wangba', 'wangwu', 'lisi', 'zhangsan'] In [30]: client.rpush('names',1) #右插 Out[30]: 5L In [31]: client.rpush('names',2) Out[31]: 6L In [32]: client.lrange('names',0,-1) Out[32]: ['wangba', 'wangwu', 'lisi', 'zhangsan', '1', '2'] In [33]: client.rpushx('names',3) #存在则右插 Out[33]: 7 In [34]: client.rpushx('namesxxx',3) Out[34]: 0 In [35]: client.lrange('names',0,-1) Out[35]: ['wangba', 'wangwu', 'lisi', 'zhangsan', '1', '2', '3'] In [36]: client.linsert('names','before',1,200) Out[36]: 8 In [37]: client.lrange('names',0,-1) Out[37]: ['wangba', 'wangwu', 'lisi', 'zhangsan', '200', '1', '2', '3'] In [38]: client.linsert('names','after',1,300) #在值之前插入 Out[38]: 9 In [39]: client.lrange('names',0,-1) Out[39]: ['wangba', 'wangwu', 'lisi', 'zhangsan', '200', '1', '300', '2', '3'] ~~~ ##B、查值 **LINDEX LPOP LRANGE RPOP** 原型: ~~~ lindex(self, name, index) method of redis.client.Redis instance Return the item from list ``name`` at position ``index`` Negative indexes are supported and will return an item at the end of the list 取列表name的index值 lpop(self, name) method of redis.client.Redis instance Remove and return the first item of the list ``name`` 删除表头元素并返回出来 rpop(self, name) method of redis.client.Redis instance Remove and return the last item of the list ``name`` 删除表尾操作并返回出来 lrange(self, name, start, end) method of redis.client.Redis instance Return a slice of the list ``name`` between position ``start`` and ``end`` ``start`` and ``end`` can be negative numbers just like Python slicing notation 取区间位置,lrange(start,stop) ~~~ ~~~ In [41]: client.lrange('names',0,-1) Out[41]: ['wangba', 'wangwu', 'lisi', 'zhangsan', '200', '1', '300', '2', '3'] In [42]: client.lindex('names',1) #index query value Out[42]: 'wangwu' In [43]: client.lpop('names') #left pop Out[43]: 'wangba' In [44]: client.rpop('names') #r eft pop Out[44]: '3' In [45]: client.lrange('names',0,-1)# 左值又值已经没了 Out[45]: ['wangwu', 'lisi', 'zhangsan', '200', '1', '300', '2'] ~~~ ##C、其它操作 **LLEN LREM LTRIM ** ~~~ llen(self, name) method of redis.client.Redis instance Return the length of the list ``name`` 返回字典元素的个数len lrem(self, name, value, num=0) method of redis.client.Redis instance Remove the first ``num`` occurrences of elements equal to ``value`` from the list stored at ``name``. 移除列表中与value相等的元素 The ``num`` argument influences the operation in the following ways: num > 0: Remove elements equal to value moving from head to tail. num < 0: Remove elements equal to value moving from tail to head. num = 0: Remove all elements equal to value. num > 0 :从表头开始向表尾搜索,移除数量为num的值 num < 0: 从表尾开始搜索,移动数量为num的值 num = 0 : 移动所有与value相等的值 有点类python里扩展分片的K ltrim(self, name, start, end) method of redis.client.Redis instance Trim the list ``name``, removing all values not within the slice between ``start`` and ``end`` ``start`` and ``end`` can be negative numbers just like Python slicing notation 对列表进行修剪,只保留start,end区间的元素,其实也就是list = list[start:stop] ~~~ ~~~ In [45]: client.lrange('names',0,-1) Out[45]: ['wangwu', 'lisi', 'zhangsan', '200', '1', '300', '2'] In [46]: In [46]: client.llen('names') Out[46]: 7 In [47]: client.lpush('names',1,1,1,1) Out[47]: 11L In [48]: client.rpush('names',1,1,1,1) Out[48]: 15L In [49]: client.lrange('names',0,-1) Out[49]: ['1', '1', '1', '1', 'wangwu', 'lisi', 'zhangsan', '200', '1', '300', '2', '1', '1', '1', '1'] In [50]: client.lrem('names',1,num=2) #num > 0 从表头开始搜索删除两个1的值 Out[50]: 2L In [51]: client.lrange('names',0,-1) Out[51]: ['1', '1', 'wangwu', 'lisi', 'zhangsan', '200', '1', '300', '2', '1', '1', '1', '1'] In [52]: client.lrem('names',1,num=-2) #num < 0 从表尾开始搜索删除两个1的值 Out[52]: 2L In [53]: client.lrange('names',0,-1) Out[53]: ['1', '1', 'wangwu', 'lisi', 'zhangsan', '200', '1', '300', '2', '1', '1'] In [54]: client.lrem('names',1,num=0) #num = 0 全册 Out[54]: 5L In [55]: client.lrange('names',0,-1) Out[55]: ['wangwu', 'lisi', 'zhangsan', '200', '300', '2'] In [57]: client.ltrim('names',2,4) #list = list[2:4] Out[57]: True In [58]: client.lrange('names',0,-1) Out[58]: ['zhangsan', '200', '300'] ~~~ #7、集合 集合的概念引入数学,集合内元素是不能相同的,集合具有交集、并集、差集这几个特性。 > SADD 将一个或多个元素添加到集合中 > SCARD 返回集合里元素的个数 > SDIFF 判断不同集的差集 > SDIFFSTORE 不同集合的差集存储为另一个集合 > SINTER 求交集 > SINTERSTORE 求交集并存储为另一个集合 > SISMEMBER 求成员关系 > SMEMBERS 返回集合中所有元素 > SMOVE 将源集合的元素移到目标集合 > SPOP 移除并返回集合中随机数,因为是无序 > SRANDMEMBER 返回count个随便元素 > SREM 移动一个或多个元素,不存在则忽略 > SUNION 求并集 > SUNIONSTORE 求并集并存储 ##A、修改操作元素 **SADD、SMOVE、SPOP、SREM** 原型: ~~~ sadd(self, name, *values) method of redis.client.Redis instance Add ``value(s)`` to set ``name`` 添加一个或多个元素到集合name中,注意values是位置传参,并且集合相同元素 smove(self, src, dst, value) method of redis.client.Redis instance Move ``value`` from set ``src`` to set ``dst`` atomically 移动src的value到dst集合中 spop(self, name) method of redis.client.Redis instance Remove and return a random member of set ``name`` 删除并返回集合name中随机一个元素,randmember方法随机返回但不删除。 srem(self, name, *values) method of redis.client.Redis instance Remove ``values`` from set ``name`` 从集合name中删除一个或多个元素 ~~~ ~~~ In [98]: client.sadd('computers','apple') #添加单个 Out[98]: 1 In [99]: client.sadd('computers','dell','lenvo') #添加多个 Out[99]: 2 In [100]: client.smembers('computers') #列出所有元素 Out[100]: {'apple', 'dell', 'lenvo'} In [102]: client.smove('computers','food','apple')#移动com元素到food Out[102]: True In [103]: client.smembers('computers') # 无apple Out[103]: {'dell', 'lenvo'} In [104]: client.smembers('food') # apple Out[104]: {'apple'} In [105]: client.spop('computers') # 删除并返回一个随机元素 Out[105]: 'dell' In [106]: client.smembers('computers') # Out[106]: {'lenvo'} In [107]: client.srem('computers','lenvo') #删除lenvo Out[107]: 1 In [108]: client.smembers('computers') # Out[108]: set() ~~~ ##B、查看元素 **SCARD SMEMBERS SRANDMEMBER ** ~~~ scard(self, name) method of redis.client.Redis instance Return the number of elements in set ``name`` 返回集合name的元素个数 smembers(self, name) method of redis.client.Redis instance Return all members of the set ``name`` 返回集合name的所有元素,结果为一个集合类型 srandmember(self, name, number=None) method of redis.client.Redis instance If ``number`` is None, returns a random member of set ``name``. 如果number为空,返回一个随便元素。 If ``number`` is supplied, returns a list of ``number`` random memebers of set ``name``. Note this is only available when running Redis 2.6+. 如果给定number返回随机number个元素,注意大于redis 2.6可用 ~~~ ~~~ In [114]: client.smembers('computers') Out[114]: {'dell', 'lenvo', 'mac', 'samsung'} In [115]: client.scard('computer') Out[115]: 0 In [116]: client.scard('computers') Out[116]: 4 In [117]: client.srandmember('computers') Out[117]: 'samsung' ~~~ 我的版本2.4就不测试了 ##C、交、并、差集 **SDIFF SDIFFSTORE SINTER SINTERSTORE SUNION SUNIONSTORE** 原型 ~~~ sdiff(self, keys, *args) method of redis.client.Redis instance Return the difference of sets specified by ``keys`` 返回一个keys与 #args的差集 不存在的key即为空集 sdiffstore(self, dest, keys, *args) method of redis.client.Redis instance Store the difference of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. 与sdiff差不多,但将结果写入dest这个集合,会进行覆盖操作,返回这个新集合的元素个数 sinter(self, keys, *args) method of redis.client.Redis instance Return the intersection of sets specified by ``keys`` 返回一个keys与args的交集 sinterstore(self, dest, keys, *args) method of redis.client.Redis instance Store the intersection of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. 与sinter差不多,但将结果写入dest这个集合,会进行覆盖操作,返回这个新集合的元素个数 sunion(self, keys, *args) method of redis.client.Redis instance Return the union of sets specified by ``keys`` 返回一个keys与args的并集 sunionstore(self, dest, keys, *args) method of redis.client.Redis instance Store the union of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. 与sunion差不多,但将结果写入dest这个集合,会进行覆盖操作,返回这个新集合的元素个数 ~~~ ~~~ In [128]: client.smembers('computers') Out[128]: {'dell', 'lenvo', 'mac', 'samsung'} In [129]: client.sadd('com2','dell','mac','mysql','google') Out[129]: 4 In [130]: client.sdiff('computers','com2') #求差集 Out[130]: {'lenvo', 'samsung'} In [131]: client.sdiffstore('waiguo','computers','com2') #求差集存储 Out[131]: 2 In [132]: client.smembers('waiguo') Out[132]: {'lenvo', 'samsung'} In [133]: client.sinter('computers','com2') #求交集 Out[133]: {'dell', 'mac'} In [134]: client.sinterstore('guide','computers','com2') #求交集并存储 Out[134]: 2 In [135]: client.smembers('guide') Out[135]: {'dell', 'mac'} In [136]: client.sunion('computers','com2') #求合集 Out[136]: {'dell', 'google', 'lenvo', 'mac', 'mysql', 'samsung'} In [137]: client.sunionstore('allcomputers','computers','com2') #求合集并存储 Out[137]: 6 In [138]: client.smembers('allcomputers') Out[138]: {'dell', 'google', 'lenvo', 'mac', 'mysql', 'samsung'} ~~~ ##D、其它操作 **SISMEMBER** ~~~ sismember(self, name, value) method of redis.client.Redis instance Return a boolean indicating if ``value`` is a member of set ``name`` 判断成员关系 ~~~ ~~~ In [143]: client.smembers('computers') Out[143]: {'dell', 'lenvo', 'mac', 'samsung'} In [144]: client.sismember('computers','mysql') #不在成员关系 Out[144]: False In [145]: client.sismember('computers','mac') #在成员关系 Out[145]: True ~~~ #8、有序集合 有序集合呢是一个集合,有两个概念一个是rank rank对应我们的下标,score对应我们value,有点像不正常的字典的列表((key,score),(key,score)),但是又能提供对score进行比较的结果。 > ZADD 将一个或多个member元素及其score值加入到有序集key当中。 > ZREM 移除有序集key中的一个或多个成员,不存在的成员将被忽略。 > ZCARD 返回有序集key的基数。 > ZCOUNT 返回有序集key中,score值在min和max之间(默认包括score值等于min或max)的成员。 > ZSCORE 返回有序集key中,成员member的score值。 > ZINCRBY 为有序集key的成员member的score值加上增量increment。 > ZRANGE 返回有序集key中,指定区间内的成员。 > ZREVRANGE 返回有序集key中,指定区间内的成员。 > ZRANGEBYSCORE 返回有序集key中,所有score值介于min和max之间(包括等于min或max)的成员。有序集成员按score值递增(从小到大)次序排列。 > ZREVRANGEBYSCORE 返回有序集key中,score值介于max和min之间(默认包括等于max或min)的所有的成员。有序集成员按score值递减(从大到小)的次序排列。 > ZRANK 返回有序集key中成员member的排名。其中有序集成员按score值递增(从小到大)顺序排列。 > ZREVRANK 返回有序集key中成员member的排名。其中有序集成员按score值递减(从大到小)排序。 > ZREMRANGEBYRANK 移除有序集key中,指定排名(rank)区间内的所有成员。 > ZREMRANGEBYSCORE 移除有序集key中,所有score值介于min和max之间(包括等于min或max)的成员。 > ZINTERSTORE 计算给定的一个或多个有序集的交集,其中给定key的数量必须以numkeys参数指定,并将该交集(结果集)储存到destination。 > ZUNIONSTORE 计算给定的一个或多个有序集的并集,其中给定key的数量必须以numkeys参数指定,并将该并集(结果集)储存到destination。 ##A、修改 **ZADD ZREM ZINCRBY ZREMRANGEBYRANK ZREMRANGEBYSCORE** 原型: ~~~ zadd(self, name, *args, **kwargs) method of redis.client.Redis instance NOTE: The order of arguments differs from that of the official ZADD command. For backwards compatability, this method accepts arguments in the form of name1, score1, name2, score2, while the official Redis documents expects score1, name1, score2, name2. If you're looking to use the standard syntax, consider using the StrictRedis class. See the API Reference section of the docs for more information. Set any number of element-name, score pairs to the key ``name``. Pairs can be specified in two ways: As *args, in the form of: name1, score1, name2, score2, ... or as **kwargs, in the form of: name1=score1, name2=score2, ... #挺简单的,就是需要注意一个传入的顺序,可以用字典传参 与命令真好相反,我们要传的是 key,score,key,score而redis命令行则正好相反。 The following example would add four values to the 'my-key' key: redis.zadd('my-key', 'name1', 1.1, 'name2', 2.2, name3=3.3, name4=4.4) 混合传参的方式 zrem(self, name, *values) method of redis.client.Redis instance Remove member ``values`` from sorted set ``name`` 删除元素key zincrby(self, name, value, amount=1) method of redis.client.Redis instance Increment the score of ``value`` in sorted set ``name`` by ``amount`` 对集合name的key进行+1操作,其实就是key:score的方式,如果amount为负数就是进行减法操作。 zremrangebyrank(self, name, min, max) method of redis.client.Redis instance Remove all elements in the sorted set ``name`` with ranks between ``min`` and ``max``. Values are 0-based, ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements removed 删除区间rank,min< del < max 这里的rank需要注意的是指的下标 zremrangebyscore(self, name, min, max) method of redis.client.Redis instance Remove all elements in the sorted set ``name`` with scores between ``min`` and ``max``. Returns the number of elements removed. 删除区间score中的元素,这里的score指的是value值 ~~~ ~~~ In [178]: client.zadd('por','zwhset',1000,'zhangsan',2000,'lisi',1500,'wangru',5000) Out[178]: 4 In [179]: client.zrange('por',0,-1) Out[179]: ['zwhset', 'lisi', 'zhangsan', 'wangru'] In [180]: client.zrem('por','lisi') #干掉李四 Out[180]: 1 In [181]: client.zrange('por',0,-1) Out[181]: ['zwhset', 'zhangsan', 'wangru'] In [182]: client.zincrby('por','zwhset',2000) # zwhset 加2000块钱 Out[182]: 3000.0 In [183]: client.zrange('por',0,-1) Out[183]: ['zhangsan', 'zwhset', 'wangru'] In [184]: client.zremrangebyrank('por',0,0) #这里注意删除的时候会删除包括下标为j 0的元素 Out[184]: 1 In [185]: client.zrange('por',0,-1) Out[185]: ['zwhset', 'wangru'] In [186]: client.zremrangebyscore('por',1000,1500) #删除工资在1000-1500的员工 Out[186]: 0 ~~~ ##B、查询 **ZCARD ZCOUNT ZSCORE ZRANGE ZREVERANGE ZRANGEBYSCORE ZREVRANGEBYSCORE ZRNK ZREVRANK** 原型: ~~~ zcard(self, name) method of redis.client.Redis instance Return the number of elements in the sorted set ``name`` 获取有序集合name中的元素个数 zcount(self, name, min, max) method of redis.client.Redis instance Returns the number of elements in the sorted set at key ``name`` with a score between ``min`` and ``max``. 返回有序集合name的score在min与max的元素个数 zscore(self, name, value) method of redis.client.Redis instance Return the score of element ``value`` in sorted set ``name`` 获取有序集合name中的key的score值,很奇怪就是各种name value zrange(self, name, start, end, desc=False, withscores=False, score_cast_func=<type 'float'>) method of redis.client.Redis instance Return a range of values from sorted set ``name`` between 返回socres区间的元素,以scores从小到大排序 ``start`` and ``end`` sorted in ascending order. start 和 end 为下标 ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly 是否正序还是倒序 ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs 是否把score的值一起返回出来,结果是 [('wangru', 5000.0), ('zwhset', 3000.0)]列表 ``score_cast_func`` a callable used to cast the score return value 这是一个回调函数 zrevrange(self, name, start, end, withscores=False, score_cast_func=<type 'float'>) method of redis.client.Redis instance 和上面那个一样,以scores从大到小排序 Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in descending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``withscores`` indicates to return the scores along with the values The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value zrangebyscore(self, name, min, max, start=None, num=None, withscores=False, score_cast_func=<type 'float'>) method of redis.client.Redis instance Return a range of values from the sorted set ``name`` with scores between ``min`` and ``max``. 返回socre区间的元素,所以min max要给定socre If ``start`` and ``num`` are specified, then return a slice of the range. ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs 结果是不是也给socre `score_cast_func`` a callable used to cast the score return value zrevrangebyscore(self, name, max, min, start=None, num=None, withscores=False, score_cast_func=<type 'float'>) method of redis.client.Redis instance Return a range of values from the sorted set ``name`` with scores between ``min`` and ``max`` in descending order. If ``start`` and ``num`` are specified, then return a slice of the range. ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value 和上面一样,反转后返回 需要注意的是先给定max再给定min不要给反了 zrank(self, name, value) method of redis.client.Redis instance Returns a 0-based value indicating the rank of ``value`` in sorted set ``name`` 返回某个元素的排名,需要注意的是0是最底的 zrevrank(self, name, value) method of redis.client.Redis instance Returns a 0-based value indicating the descending rank of ``value`` in sorted set ``name`` 返回某个元素的倒序排名 ~~~ In [197]: client.zrange('por',0,-1,withscores=True) #返回区间下标 Out[197]: [('zwhset', 3000.0), ('wangru', 5000.0)] In [198]: client.zcard('por') #元素个数 Out[198]: 2 In [199]: client.zcount('por',3000,4000) # scores内元素个数 Out[199]: 1 In [200]: client.zcount('por',3000,5000) Out[200]: 2L In [201]: client.zscore('por','zwhset') #查看元素的score Out[201]: 3000.0 In [202]: client.zrange('por',0,-1) Out[202]: ['zwhset', 'wangru'] In [203]: client.zrange('por',0,-1,desc=True) #倒序 Out[203]: ['wangru', 'zwhset'] In [204]: client.zrange('por',0,-1,desc=True,withscores=True) #显示score Out[204]: [('wangru', 5000.0), ('zwhset', 3000.0)] In [205]: client.zrevrange('por',0,-1) #反转显示 Out[205]: ['wangru', 'zwhset'] In [212]: client.zrevrangebyscore('por',5000,3000,withscores=True) #注意顺序 Out[212]: [('wangru', 5000.0), ('zwhset', 3000.0)] In [213]: client.zrank('por','zwhset') #获了元素的排名 Out[213]: 0 In [218]: client.zrank('por','wangru') Out[218]: 1 In [219]: client.zrevrank('por','zwhset') #反序排名 Out[219]: 1 In [220]: client.zrevrank('por','wangru') Out[220]: 0 ##C、集合特性 **ZINTERSTORE ZUNIONSTORE** 原型 ~~~ zinterstore(self, dest, keys, aggregate=None) method of redis.client.Redis instance Intersect multiple sorted sets specified by ``keys`` into a new sorted set, ``dest``. Scores in the destination will be aggregated based on the ``aggregate``, or SUM if none is provided. 求交集并存储为dest集合,aggregate是算法,默认为sum和 还有min max的参数 aggregate叫做结果集的聚合方式 zunionstore(self, dest, keys, aggregate=None) method of redis.client.Redis instance Union multiple sorted sets specified by ``keys`` into a new sorted set, ``dest``. Scores in the destination will be aggregated based on the ``aggregate``, or SUM if none is provided. 求合集并存储为dest集合,其它的和上面一样 ~~~ ~~~ In [225]: client.zrange('pro',0,-1,withscores=True) Out[225]: [] In [226]: client.zrange('por',0,-1,withscores=True) Out[226]: [('zwhset', 3000.0), ('wangru', 5000.0)] In [227]: client.zadd('por1','zwhset',5000,'wangru',8000,'lisi',9000) Out[227]: 3 In [230]: client.zinterstore('newpor',('por','por1')) #两公司合并,求交集员工工资相加 Out[230]: 2L In [231]: client.zrange('newpor',0,-1,withscores=True) Out[231]: [('zwhset', 8000.0), ('wangru', 13000.0)] In [233]: client.zunionstore('newpor',('por','por1')) #两公司合并,求合集,员工工资相加 Out[233]: 3L In [234]: client.zrange('newpor',0,-1,withscores=True) Out[234]: [('zwhset', 8000.0), ('lisi', 9000.0), ('wangru', 13000.0)] In [235]: client.zunionstore('newpor',('por','por1'),aggregate='min') #两公司合并,求交集,员工工资取最小的 Out[235]: 3L In [236]: client.zrange('newpor',0,-1,withscores=True) Out[236]: [('zwhset', 3000.0), ('wangru', 5000.0), ('lisi', 9000.0)] ~~~ #9、订阅发布 ~~~ pubsub(self, **kwargs) method of redis.client.Redis instance Return a Publish/Subscribe object. With this object, you can subscribe to channels and listen for messages that get published to them. 返回一个订阅发布对象 ~~~ pubsub对象具有的方法 > '_execute', > 'channels', 获取你订阅的频道 > 'close', 关闭你订阅的频道链接 > 'connection', 返回你的连接信息 > 'connection_pool', 创建一个连接池,和我们redis连接方式小节相同 > 'decode_responses', > 'encode', > 'encoding', > 'encoding_errors', > 'execute_command', 执行一个发布或订阅的命令 > 'get_message', 获取一个订阅的消息 > 'handle_message', 保持获取一个连接信息 > 'ignore_subscribe_messages', > 'listen', 监听从一个频道里订阅的消息 > 'on_connect', 重新订阅刚才发布的东西 > 'parse_response', 解析返回对象 > 'patterns', > 'psubscribe', 订阅频道 > 'punsubscribe',取消订阅 > 'reset', > 'run_in_thread', > 'shard_hint', > 'subscribe', > 'subscribed', > 'unsubscribe' github上面的一个发布订阅代码,采用多线程的方式 ~~~ import redis import threading class Listener(threading.Thread): def __init__(self, r, channels): threading.Thread.__init__(self) self.redis = r self.pubsub = self.redis.pubsub() self.pubsub.subscribe(channels) def work(self, item): print item['channel'], ":", item['data'] def run(self): for item in self.pubsub.listen(): if item['data'] == "KILL": self.pubsub.unsubscribe() print self, "unsubscribed and finished" break else: self.work(item) if __name__ == "__main__": r = redis.Redis() client = Listener(r, ['test']) client.start() r.publish('test', 'this will reach the listener') r.publish('fail', 'this will not') r.publish('test', 'KILL') ~~~