Redis Python and redispython

Source: Internet
Author: User
Tags install redis

Redis Python and redispython

Infi-chu:

Http://www.cnblogs.com/Infi-chu/

 

NoSQL (NoSQL = Not Only SQL) means non-relational databases in Chinese.

With the rise of Internet Web websites, traditional relational databases are dealing with Web websites, especially ultra-large-scale and high-concurrency SNS type pure Dynamic Web websites, which have exposed many insurmountable problems, non-relational databases have developed rapidly due to their own characteristics.

Advantages of NoSQL:

Disadvantages of NoSQL:

Four types of NoSQL databases:

Comparison:

Redis

Redis is one of the mainstream key-value nosql databases in the industry. Similar to Memcached, Memcached supports more storage value types, including string, list, set, and zset) and hash (hash type ). These data types support push/pop, add/remove, Intersection Set and difference set, and more abundant operations, and these operations are atomic. On this basis, redis supports sorting in different ways. Like memcached, data is cached in the memory to ensure efficiency. The difference is that redis periodically writes the updated data to the disk or writes the modification operation to the append record file, and on this basis implements master-slave (master-slave) synchronization.

Advantages of Redis:

Python operations on Redis

Pip install redis

Some useful operations
Ps-ef | grep redis view Process status netstat-tulnp view port number redis-cli local connection Redis

  

 

Redis API (redis-py) can be used in five categories:

I. Connection Method

Operation Mode:

#import redis#a=redis.Redis(host='192.168.1.1',port=6379)#a.set('foo','Bar')#print(r.get('foo'))

  

 

Ii. Connection Pool

Redis-py uses the connection pool to manage all connections of a redis server, avoiding the overhead of establishing and releasing connections each time.

By default, each Redis instance maintains its own connection pool. You can directly create a connection pool and use it as the parameter Redis, so that multiple Redis instances can share a connection pool.

Iii. Operations

1. String operation:

The memory is stored according to a name corresponding to a value, one-to-one relationship


# Terminal Syntax: # set name bob # Save # get name # get # keys * # retrieve all key values # set name sam ex 3 # automatically delete after 3 seconds

 

1. string operation: stores data in the memory according to a name corresponding to a value, with a corresponding relationship # python Syntax: # set (name, value, ex = None, px = None, nx = False, xx = False) # set the value in Redis. It is created by default if no value exists. If yes, modify it. # parameter: # ex: expiration time (seconds) # px: expiration time (MS) # nx: If set to True, the current set is executed only when the name does not exist # xx: If set to True, only when the name exists, the current set operation is executed # setnx (name, value) # set value. It is executed only when name does not exist # setex (name, value, time) # set value, time is the expiration time (seconds) # psetex (name, time_ms, value) # set the value, time_ms expiration time (milliseconds) # mset (* args, ** kwargs) # batch set values # example: mset (n1 = 'A', n2 = 'B ') Or mget ({'n1': 'A', 'n2 ':' B '}) # get (name) # get value # mget (keys, * args) # batch acquisition # example: mget ('a1', 'a2 ') or r. mget (['a1', 'a2 ']) # getset (name, value) # set a new value and obtain the original value # getrange (key, start, end) # obtain the subsequence (start byte, end byte) # setrange (name, offset, value) # modify the string content and replace it from the specified position, if the value is exceeded, it is added with # offset, string index, byte (one Chinese character is 3 bytes) # value, value to be set # setbit (name, offset, value) # perform operations on the bit of the binary representation of the value corresponding to name # name: name # offset: Index of the BIT (convert the value to binary before indexing) # value: it can only be 0 or 1 # getbit (name, offset )# Obtain the binary representation of the value corresponding to name. # bitcount (key, start = None, end = None) # obtain the number of 1 in the binary representation of the value corresponding to name # strlen (name) # Return the byte length of the value corresponding to name # incr (self, name, amount = 1) # value corresponding to auto-increment and name. If the name does not exist, create name = amount. Otherwise, auto-increment # amount is auto-increment # incrbyfloat (self, name, amount = 1.0) # floating point type # decr (self, name, amount = 1) # values corresponding to auto-subtraction and name. If the name does not exist, create name = amount, otherwise, auto-Subtract # append (key, value) # In Redis, the content appended to the value corresponding to name 2. the Hash operation is similar to the dictionary in python. It can store a group of highly correlated data. One-to-one relationships also correspond to each other. # hset (name, key, Value) # Set a key-value pair in the hash corresponding to name (if any, it is modified, or not created) # name: name # key in the value corresponding to key: name # value: values in the value corresponding to name # hmset (name, mapping) # batch set key-value pairs in the hash corresponding to name # example: r. hmset ('A', {'b1 ': 'Q', 'b2': 'W'}) # hget (name, key) # in the group corresponding to name, obtain value # hmet (name, keys, * args) based on key # obtain the value of multiple keys in the group corresponding to name # hgetall (name) # obtain all key values in the group corresponding to name # hlen (name) # obtain the number of key-value pairs in the group corresponding to name # hkeys (name) # obtain the group corresponding to name, value of all keys # hvals (name) # obtain the value of all values in the group corresponding to name # hexists (name, key) # Check the group corresponding to name, Whether the currently passed key # hdel (name, * keys) # Delete the key-value pair of the specified key in the group corresponding to name # hincrby (name, key, amount = 1) # in the group corresponding to the auto-increment name, specify the key value. If the value does not exist, create key = amount # hincrbyfloat (name, key, amount = 1.0) # Floating Point auto-increment # hscan (name, cursor = 0, match = None, count = None) # incremental iterative acquisition, which is very useful for big data, hscan can be used to obtain data in parts, instead of getting all the data at a time, so that the memory is exposed. # parameter: # name, redis name # cursor, cursor (obtain data in batches Based on the cursor) # match: match the specified key. By default, None indicates all keys # count. The minimum number of retrieved parts is allowed, the default value "None" indicates the default number of shards using Redis # For example: # first time: cu Rsor1, data1 = r. hscan ('XX', cursor = 0, match = None, count = None) # Second: cursor2, data1 = r. hscan ('XX', cursor = cursor1, match = None, count = None )#... # Until the returned value of cursor is 0, it indicates that the data has been obtained through the shard. 3. A name in the list operation corresponds to a list # lpush (name, values) # add elements to the list corresponding to name, and add each new element to the leftmost of the list # rpush (name, values) indicates the right-to-left operation # lpushx (name, value) # Add an element to the list corresponding to name. Only when name already exists, add the value to the leftmost part of the list # rpushx (name, value) indicates the right-to-left operation # llen (name) # list element corresponding to name Count # linsert (name, where, refvalue, value) # Insert a new value before or after a value in the list corresponding to name # parameter: # name, redis name # where, BEFORE or AFTER # refvalue, benchmark value, that is: insert data BEFORE and AFTER it # value, data to be inserted # r. lrem (name, value, num) # Delete the specified value from the list corresponding to name # parameter: # name, redis name # value, value to be deleted # num, num = 0, delete all the specified values in the list # num = 2, from the past to the next, delete 2 # num =-2, from the back to the front, delete 2 # lpop (name) # retrieve the first element on the left of the list corresponding to name and remove it from the list. The returned value is the first element # rpop (name) indicates the right-to-left operation # lindex (name, index) # obtain the list elements based on the index in the list corresponding to the name # lra Nge (name, start, end) # obtain data in the list shard corresponding to name # parameter: # name, redis name # start, index start position # end, index end position # ltrim (name, start, end) # Remove the value between the start-end indexes from the list corresponding to name # parameter: # name, redis name # start, index start position # end, index end position # rpoplpush (src, dst) # retrieve the rightmost element from a list, at the same time, add it to the leftmost # parameter of another list: # src, name of the list to be retrieved # dst, name of the list to be added # blpop (keys, timeout) # arrange multiple lists according to the elements in the pop list from left to right # parameter: # keys, redis name set # timeout, timeout time, after all the elements in the element list are obtained, blocking waits for Data time (in seconds). 0 indicates permanent blocking # r. brpop (keys, timeout), get data from right to left # brpoplpush (src, dst, timeout = 0) # remove an element from the right of a list and add it to the left of another list # parameter: # src, retrieve and remove the name # dst corresponding to the list of elements, name # timeout corresponding to the list of elements to be inserted. If no data exists in the list corresponding to src, blocking waits for the timeout time (in seconds) for the data to be inserted. 0 indicates blocking forever. 4. the set operation is a list that does not allow repeated operations # sadd (name, values) # add elements to the set corresponding to name # scard (name) # obtain the number of elements in the set corresponding to name # sdiff (keys, * args) # Element Set of the set corresponding to the first name and not corresponding to other names # sdiffstore (dest, keys, * args) # obtain the set corresponding to the first name # Sinter (keys, * args) # obtain the union of the set with one more name # sinterstore (dest, keys, * args) # obtain the union of the set with one more name, add it to the set corresponding to dest # sismember (name, value) # Check whether value is a member of the set corresponding to name # smembers (name) # Getting all members of the set corresponding to name # smove (src, dst, value) # moving a member from one set to another # spop (name) # Remove a member from the right (tail) of the Set and return it # srandmember (name, numbers) # obtain numbers elements randomly from the set corresponding to name # srem (name, values) # delete some values in the set corresponding to name # sunion (ke Ys, * args) # obtain the union of the set corresponding to one more name # sunionstore (dest, keys, * args) # obtain the union of the set corresponding to one more name, save the result to the collection corresponding to dest # sscan (name, cursor = 0, match = None, count = None) # sscan_iter (name, match = None, count = None) # operations with the same string are used to obtain elements in batches through incremental iteration to avoid high memory consumption # zadd (name, * args, ** kwargs) # add elements to the sorted set corresponding to name # For example: # zadd ('zz ', 'n1', 1, 'n2 ', 2) # Or # zadd ('zz ', n1 = 11, n2 = 22) # zcard (name) # obtain the number of elements in the sorted set corresponding to name # zcount (name, min, max) # obtain the scores in the sorted set corresponding to the name in Number between [min, max] # zincrby (name, value, amount) # Score corresponding to the name of the ordered set corresponding to the auto-increment name # r. zrange (name, start, end, desc = False, withscores = False, score_cast_func = float) # obtain the elements of the sorted set corresponding to name according to the index range # parameter: # name, redis name # start, starting position of an ordered set index (non-score) # end, ending position of an ordered set index (non-score) # desc, sorting rule, by default, scores are sorted from small to large. # withscores: determines whether to obtain the score of an element. By default, only the value of an element is obtained. # score_cast_func is used to convert scores. # more: # sort from big to small # zrevrange (name, start, end, withscores = False, score_cast _ Func = float) # element of the sorted set corresponding to name obtained according to the score range # zrangebyscore (name, min, max, start = None, num = None, withscores = False, score_cast_func = float) # sort from big to small # zrevrangebyscore (name, max, min, start = None, num = None, withscores = False, score_cast_func = float) # zrank (name, value) # obtain the ranking of a value in the ordered set corresponding to name (starting from 0) # More: # zrevrank (name, value), ascending order # zrem (name, values) # The value of the sorted set corresponding to the delete name is a member of values # For example, zrem ('zz ', ['s1', 's2']) # zre Mrangebyrank (name, min, max) # Delete by ranking range # zremrangebyscore (name, min, max) # Delete by score range # zscore (name, value) # obtain the score corresponding to the value in the ordered set corresponding to the name # zinterstore (dest, keys, aggregate = None) # obtain the intersection of the two ordered sets. If the same value has different scores, perform operations according to aggregate # The value of aggregate is sum min max # zunionstore (dest, keys, aggregate = None) # obtain the Union set of two ordered sets. If the same value is different, perform operations according to aggregate # The value of aggregate is: sum min max # zscan (name, cursor = 0, match = None, count = None, score_c Ast_func = float) # zscan_iter (name, match = None, count = None, score_cast_func = float) # similar to the string, compared to the new score_cast_func string, used to perform the score operation 5. other operations # delete (* names) # delete any data type in redis # exists (name) # Check whether the redis name exists # keys (pattern = '*') # obtain the redis name based on the model # More: # KEYS * matches all KEYS in the database. # KEYS h? Llo matches hello, hallo, and hxllo. # KEYS h * llo matches hllo and heeeeello. # KEYS h [AE] llo matches hello and hallo, but does not match hillo # expire (name, time) # sets the timeout time for a name of a redis # rename (src, dst) # rename redis name to # move (name, db) # move a redis value to a specified db # randomkey () # randomly retrieve a redis name (not deleted) # type (name) # obtain the type of the value corresponding to the name # scan (cursor = 0, match = None, count = None) # scan_iter (match = None, count = None) # same string operation, used for incremental iteration to get the key

  

Iv. Pipelines

By default, redis-py creates (the connection pool applies for connection) and disconnects (returns the connection pool) each time a request is executed. If you want to specify multiple commands in a request, you can use pipline to specify multiple commands for one request. By default, pipline is an atomic operation.

5. Publish and subscribe

Let people know the content of something

 

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.