Python's Redis module

Source: Internet
Author: User
Tags memcached ord set set redis server

I. Introduction of Redis

Redis is a key-value storage system. Similar to memcached, it supports storing more value types, including string (string), list (linked list), set (set), Zset (sorted set-ordered collection), and hash (hash type). These data types support Push/pop, Add/remove, and intersection-set and difference sets, and richer operations, and these operations are atomic. Based on this, Redis supports sorting in a variety of different ways. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to disk or writes the modified operation to the appended record file, and Master-slave (Master-Slave) synchronization is implemented on this basis.

Redis is a high-performance Key-value database. The emergence of Redis, to a large extent, compensates for the lack of memcached such key/value storage, in some cases can be a good complement to the relational database. It provides the python,ruby,erlang,php client, which is easy to use and Redis supports master-slave synchronization. Data can be synchronized from the primary server to any number of slave servers, from the server to the primary server that is associated with other slave servers. This enables Redis to perform single-layer tree replication. The data can be written intentionally or unintentionally from the disk. Because of the full implementation of the publish/subscribe mechanism, you can subscribe to a channel and receive a complete message release record from the master server when the tree is synchronized anywhere from the database.

Second, Python link redis mode 2.1 normal link mode

Redis-py provides two classes of Redis and Strictredis for implementing Redis commands, Strictredis is used to implement most of the official commands, and using official syntax and commands, Redis is a subclass of Strictredis

#!/usr/bin/env python#-*-coding:utf-8-*-import redisr = Redis. Redis (host= ' 192.168.0.110 ', port=6379,db=0) r.set (' name ', ' Zhangsan ')   #添加print (r.get (' name '))   #获取
2.2 Link Pool

Redis-py uses connection pool to manage all connections to a Redis server, avoiding the overhead of each establishment and release of the connection. By default, each Redis instance maintains its own pool of connections. You can create a connection pool directly, and then as a parameter Redis, you can implement multiple Redis instances to share a single connection pool.

#!/usr/bin/env python#-*-coding:utf-8-*-import redispool = Redis. ConnectionPool (host= ' 192.168.0.110 ', port=6379) R = Redis. Redis (Connection_pool=pool) r.set (' name ', ' Zhangsan ')   #添加print (r.get (' name '))   #获取
2.3 Piping

Redis-py The default is to create each request (Connection pool request connection) and disconnect (return connection pool) One connection operation, if you want to specify more than one command in a single request, you can use Pipline to implement a single request to specify multiple commands, and by default Pipline is an atomic operation.

#!/usr/bin/env python#-*-coding:utf-8-*-import redispool = Redis. ConnectionPool (host= ' 192.168.0.110 ', port=6379) R = Redis. Redis (connection_pool=pool) pipe = R.pipeline (transaction=true) r.set (' name ', ' Zhangsan ') r.set (' name ', ' Lisi ') Pipe.execute ()
2.4 Publications and subscriptions

First define a Redishelper class, connect Redis, define the channel as monitor, define the publish (publish) and subscribe (subscribe) methods.

#!/usr/bin/env python#-*-coding:utf-8-*-import redisclass redishelper (object):    def __init__ (self):        self.__ conn = Redis. Redis (host= ' 192.168.0.110 ', port=6379) #连接Redis        self.channel = ' monitor ' #定义名称    def publish (self,msg): #定义发布方法        self.__conn.publish (self.channel,msg)        return True    def subscribe (self): #定义订阅方法        pub = self.__ Conn.pubsub ()        pub.subscribe (Self.channel)        pub.parse_response ()        return pub

Published by

#!/usr/bin/env python#-*-coding:utf-8-*-#发布from redishelper Import redishelperobj = Redishelper () obj.publish (' Hello ' ) #发布

Subscribed by

#!/usr/bin/env python#-*-coding:utf-8-*-#订阅from redishelper Import redishelperobj = Redishelper () redis_sub = OBJ.SUBSC Ribe () #调用订阅方法while True:    msg= redis_sub.parse_response ()    print (msg)
Three, Python-redis module Operation command

Redis supports five data types: string, Hash (dictionary in Python, nested dictionary As String when dictionary is nested), list, set (set), ordered collection

3.1String operation

The string in Redis is stored in memory by a name corresponding to a value

Set ()

#在Redis中设置值, default does not exist then create, present modify R.set (' name ', ' Zhangsan ') ' parameter:     set (name, value, Ex=none, Px=none, Nx=false, Xx=false)     EX, Expiration Time (seconds)     px, Expiration Time (ms)     NX, if set to true, the current set operation executes only if name does not exist, with SETNX (name, value)     xx, if set to true, The current set operation only executes "Setex" (name, value, time) #设置过期时间 (seconds) Psetex (name, Time_ms, value) #设置过期时间 (Hao seconds) when only name exists

Mset ()

#批量设置值r. Mset (name1= ' Zhangsan ', name2= ' Lisi ') #或r. Mget ({"name1": ' Zhangsan ', "name2": ' Lisi '})

Get (name)

Get value

Mget (keys, *args)

#批量获取print (R.mget ("name1", "name2")) #或li =["name1", "Name2"]print (R.mget (LI))

Getset (name, value)

#设置新值, print the original value print (R.getset ("name1", "Wangwu")) #输出: Zhangsanprint (R.get ("name1")) #输出: Wangwu

GetRange (key, start, end)

#根据字节获取子序列r. Set ("Name", "Zhangsan") Print (R.getrange ("name", 0,3)) #输出: Zhan

SETRANGE (name, offset, value)

#修改字符串内容, the backward substitution starts from the specified string index, and if the new value is too long, add R.set ("name", "Zhangsan") R.setrange ("name", "1," Z ") Print (R.get (" name ")) #输出: Zzangsanr.setrange ("Name", 6, "zzzzzzz") Print (R.get ("name")) #输出: zzangszzzzzzz

Setbit (name, offset, value)

#对二进制表示位进行操作 the name offset of the Name:redis    , the index of the bit (the ASCII code corresponding to the value is transformed into binary and then indexed) value    , which can only be 1 or 0 "str=" 345 "R.set (" Name ", str) for i in STR:    print (I,ord (i), Bin (ord (i))) #输出 value, corresponding value in ASCII code, binary ' output of corresponding value conversion:    3 0b110011    4 52 0b110100    5 0b110101 ' r.setbit ("name", 6,0) #把第7位改为0, i.e. 3 corresponds to 0b110001print (R.get ("name")) #输出: 145

Getbit (name, offset)

#获取name对应值的二进制中某位的值 (0 or 1) r.set ("Name", "3") # corresponds to the binary 0b110011print (r.getbit ("name", 5))   #输出: 0print (R.getbit (" Name ", 6))   #输出: 1

Bitcount (Key, Start=none, End=none)

#获取对应二进制中1的个数r. Set ("Name", "345") #0b110011 0b110100 0b110101print (R.bitcount ("name", start=0,end=1)) #输出: 7 "key: Redis name    start: Byte start position end    : Byte end Position ' '

strlen (name)

#返回name对应值的字节长度 (3 bytes of a kanji) r.set ("name", "Zhangsan") Print (R.strlen ("name")) #输出: 8

INCR (self, name, amount=1)

#自增mount对应的值, the Mount=amount is created when Mount does not exist, otherwise it is self-increasing, amount is the self-increment (integer) print (R.INCR ("Mount", amount=2)) #输出: 2print (R.INCR ( "Mount")) #输出: 3print (R.INCR ("Mount", amount=3) #输出: 6print (R.INCR ("Mount", amount=6)) #输出: 12print (R.get ("mount")) # Output: 12

Incrbyfloat (self, name, amount=1.0)

#类似 incr () self-increment, amount as self-increment (floating-point number)

DECR (self, name, amount=1)

#自减name对应的值, Name=amount is created when name does not exist, otherwise, amount is self-increment (integer)

Append (name, value)

#在name对应的值后面追加内容r. Set ("Name", "Zhangsan") Print (R.get ("name"))    #输出: ' Zhangsanr.append ("name", "Lisi") print ( R.get ("name"))    #输出: Zhangsanlisi
3.2Hash operation

The hash in Redis is similar to a name in memory that corresponds to a dic to store

Hset (name, key, value)

#name对应的hash中设置一个键值对 (does not exist, it is created, otherwise, modified) R.hset ("Dic_name", "A1", "AA")

Hget (Name,key)

R.hset ("Dic_name", "A1", "AA") #在name对应的hash中根据key获取valueprint (R.hget ("Dic_name", "A1")) #输出: AA

Hgetall (name)

#获取name对应hash的所有键值print (R.hgetall ("Dic_name"))

Hmset (name, mapping)

#在name对应的hash中批量设置键值对, Mapping: Dictionary dic={"A1": "AA", "B1": "BB"}r.hmset ("Dic_name", dic) print (R.hget ("Dic_name", "B1")) #输出: BB

Hmget (name, keys, *args)

# Get multiple key values in name corresponding hash li=["A1", "B1"]print (R.hmget ("Dic_name", Li)) print (R.hmget ("Dic_name", "A1", "B1"))

Hlen (name), Hkeys (name), Hvals (name)

dic={"A1": "AA", "B1": "BB"}r.hmset ("Dic_name", DIC) #hlen (name) gets the number of key-value pairs in the hash print (R.hlen ("Dic_name")) #hkeys (name) Gets the value of all keys in the hash print (R.hkeys ("Dic_name")) #hvals (name) Gets the value of all the values in the hash print (R.hvals ("Dic_name"))

Hexists (name, key)

#检查name对应的hash是否存在当前传入的keyprint (r.hexists ("Dic_name", "A1")) #输出: True

Hdel (Name,*keys)

#删除指定name对应的key所在的键值对r. Hdel ("Dic_name", "A1")

Hincrby (name, key, Amount=1)

#自增hash中key对应的值, does not exist create Key=amount (amount is an integer) print (R.hincrby ("demo", "a", amount=2))

Hincrbyfloat (name, key, amount=1.0)

#自增hash中key对应的值, does not exist create key=amount (amount as floating point)

Hscan (name, cursor=0, Match=none, Count=none)

Hscan_iter (name, Match=none, Count=none)

3.3List operation

The list in Redis is stored in memory according to a list of name

Lpush (name,values)

# add elements to the list of name, and each new element is added to the leftmost r.lpush ("List_name", 2) R.lpush ("List_name", 3,4,5) #保存在列表中的顺序为5, 4,3,2

Rpush (name,values)

#同lpush, but each new element is added to the far right of the list

Lpushx (Name,value)

#在name对应的list中添加元素, the value is added to the leftmost side of the list only if name already exists

Rpushx (Name,value)

#在name对应的list中添加元素, the value is added to the far right of the list only if name already exists

Llen (name)

# name corresponds to the number of list elements print (R.llen ("List_name"))

Linsert (name, where, Refvalue, value))

# Insert a new value before or after a value in the name corresponding list R.linsert ("List_name", "before", "2", "SS") #在列表内找到第一个元素2, insert the SS ' ' parameter before it:     name: Redis name     where:before (front) or after (POST)     Refvalue: value in List ' values '     : Data to be inserted '

R.lset (name, index, value)

#对list中的某一个索引位置重新赋值r. LSet ("List_name", 0, "BBB")

R.lrem (name, value, num)

#删除name对应的list中的指定值r. Lrem ("List_name", "SS", num=0) "parameter:    name:  redis Name value    :    num   to remove: Num=0 Delete all the specified values in the list;           num=2 from front to back, delete 2;           num=-2 from Back, remove 2 "

Lpop (name)

#移除列表的左侧第一个元素, the return value is the first element of print (R.lpop ("List_name"))

Lindex (name, index)

#根据索引获取列表内元素print (R.lindex ("List_name", 1))

Lrange (name, start, end)

#分片获取元素print (R.lrange ("List_name", 0,-1))

LTrim (name, start, end)

#移除列表内没有在该索引之内的值r. LTrim ("List_name", 0,2)

Rpoplpush (SRC, DST)

# take the rightmost element out of a list and add it to the leftmost #src of the other list #dst list of data to add

Brpoplpush (SRC, DST, timeout=0)

#同rpoplpush, a timeout, timeout: Take the list of data without the blocking time of the element, 0 is blocked R.brpoplpush ("List_name", "list_name1", timeout=0)

Blpop (keys, timeout)

#将多个列表排列, the elements in each list are removed from left to right R.lpush ("List_name", 3,4,5) R.lpush ("List_name1", 3,4,5) while True:    print (R.blpop ([" List_name "," list_name1 "],timeout=0))    print (R.lrange (" List_name ", 0,-1), R.lrange (" list_name1 ", 0,-1))" Keys: The collection of the name of the Redis timeout   : Timeout time, after the elements of all lists are blocked, the time (in seconds) to block the data in the wait list, 0 means "forever"

R.brpop (keys, timeout)

#同blpop, arrange multiple lists and remove elements from the list by right-like left

3.4Set operation

Set set is a list that does not allow duplicates

Sadd (name,values)

#给name对应的集合中添加元素r. Sadd ("Set_name", "AA") R.sadd ("Set_name", "AA", "BB")

Smembers (name)

#获取name对应的集合的所有成员

SCard (name)

#获取name对应的集合中的元素个数r. SCard ("Set_name")

Sdiff (keys, *args)

#在第一个name对应的集合中且不在其他name对应的集合的元素集合r. Sadd ("Set_name", "AA", "BB") R.sadd ("set_name1", "BB", "CC") R.sadd ("Set_name2", "BB", "CC", "DD") Print (R.sdiff ("Set_name", "set_name1", "set_name2")) #输出: {AA}

Sdiffstore (dest, Keys, *args)

#相当于把sdiff获取的值加入到dest对应的集合中

Sinter (keys, *args)

# get multiple name corresponding set of R.sadd ("Set_name", "AA", "BB") R.sadd ("set_name1", "BB", "CC") R.sadd ("set_name2", "BB", "CC", "DD") Print (R.sinter ("Set_name", "set_name1", "set_name2")) #输出: {BB}

Sinterstore (dest, Keys, *args)

#获取多个name对应集合的并集, and then add it to the dest corresponding set.

Sismember (name, value)

#检查value是否是name对应的集合内的元素

Smove (SRC, DST, value)

#将某个元素从一个集合中移动到另外一个集合

Spop (name)

#从集合的右侧移除一个元素, and return it

Srandmember (name, numbers)

# randomly get numbers elements print (R.srandmember ("Set_name2", 2) from a collection of name

Srem (name, values)

#删除name对应的集合中的某些值print (R.srem ("set_name2", "BB", "DD"))

Sunion (keys, *args)

#获取多个name对应的集合的并集r. Sunion ("Set_name", "set_name1", "set_name2")

Sunionstore (Dest,keys, *args)

#获取多个name对应的集合的并集, and save the results to the corresponding collection in Dest
3.5 ordered set

On the basis of the collection, for each element, the ordering of the elements needs to be compared according to another value, so for an ordered set, each element has two values, namely: values and fractions, which are specifically used for sorting.

Zadd (name, *args, **kwargs)

# add Element R.zadd ("Zset_name", "A1", 6, "A2", 2, "A3", 5) in the ordered set of name corresponding to #或r. Zadd (' zset_name1 ', b1=10, b2=5)

Zcard (name)

#获取有序集合内元素的数量

Zcount (name, Min, max)

Number of print (R.zcount ("Zset_name", 1,5) between #获取有序集合中分数在 [Min,max]

Zincrby (name, value, amount)

#自增有序集合内value对应的分数r. Zincrby ("Zset_name", "A1", amount=2) #自增zset_name对应的有序集合里a1对应的分数

Zrange (name, start, end, Desc=false, Withscores=false, Score_cast_func=float)

# Gets the element Aa=r.zrange ("Zset_name", 0,1,desc=false,withscores=true,score_cast_func=int) print (AA) "for the ordered collection of name corresponding to the index range Parameter:    name of    redis name    start   Ordinal collection index start position    end     ordered collection index end position    desc    collation, default by score from small to large    Withscores  whether to get the fraction of an element, by default only gets the value of the element score_cast_func the function of the    data conversion of the fraction

Zrevrange (name, start, end, Withscores=false, Score_cast_func=float)

#同zrange, the collection is sorted from large to small

Zrank (name, value), Zrevrank (name, value)

#获取value值在name对应的有序集合中的排行位置 (starting from 0) print (R.zrank ("Zset_name", "A2")) Print (R.zrevrank ("Zset_name", "A2")) #从大到小排序

Zscore (name, value)

#获取name对应有序集合中 value corresponding to the score print (R.zscore ("Zset_name", "A1"))

Zrem (name, values)

#删除name对应的有序集合中值是values的成员r. Zrem ("Zset_name", "A1", "A2")

Zremrangebyrank (name, Min, max)

#根据排行范围删除

Zremrangebyscore (name, Min, max)

#根据分数范围删除

Zinterstore (dest, Keys, Aggregate=none)

R.zadd ("Zset_name", "A1", 6, "A2", 2, "A3", 5) R.zadd (' zset_name1 ', a1=7,b1=10, b2=5) # Gets the intersection of two ordered sets and puts it into the Dest collection, if you encounter different fractions of the same value, Then follow aggregate # aggregate value is: SUM  MIN  maxr.zinterstore ("Zset_name2", ("zset_name1", "Zset_name"), Aggregate= "MAX") Print (R.zscan ("zset_name2"))

Zunionstore (dest, Keys, Aggregate=none)

#获取两个有序集合的并集并放入dest集合, the other with Zinterstore,

Other common operations

Delete (*names)

#根据name删除redis中的任意数据类型

Exists (name)

#检测redis的name是否存在

Keys (pattern= ' * ')

#根据 *? Wait for wildcard matches to get the name of a Redis

Expire (name, time)

# Set a time-out for a name

Rename (src, DST)

# rename

Move (name, DB))

# move one of the Redis values to the specified db

Randomkey ()

#随机获取一个redis的name (not deleted)

Type (name)

# Gets the type of the name corresponding value

Python's Redis module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.