Introduction to using redis in Python and introduction to pythonredis
I. Introduction to 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.
Ii. Advantages of Redis
Exception fast: Redis is very fast. It can perform about 110000 setting operations per second and 81000 read operations per second.
Supports a wide range of data types: Redis supports data types that most developers already know, such as list, set, sortedset, and hash. This makes it easy to solve various problems in applications, because we know which types of data are used to better solve the problems.
Operations are atomic: All Redis operations are atomic, so that when two customers access the Redis server at the same time, they get the updated value (the latest value ).
- MultiUtility tool: Redis is a versatile utility that can be used in many applications, such as cache and message passing queues (Redis native supports publishing/subscription). For example: web application sessions, website page clicks, and other transient data
Iii. Redis API usage
Redis-py APIs can be used in the following categories:
- Connection Method
- Connection Pool
- Operation
- String operation
- Hash operation
- List Operation
- Set operation
- Sort Set operation
- MPs queue
- Publish and subscribe
3.1 connection mode
1. Operation Mode
Redis-py provides two types of Redis and StrictRedis for implementing Redis commands. StrictRedis is used to implement most official commands and uses official syntax and commands. Redis is a subclass of StrictRedis, used for backward compatibility with the old version of redis-py.
import redishost = '172.16.200.49'port = 6379r = redis.Redis(host=host, port=port)r.set('foo', 'bar')print(r.get('foo'))
2. Connection Pool
Redis-py uses the connection pool to manage all connections to 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.
import redishost = '172.16.200.49'port = 6379pool = redis.ConnectionPool(host=host, port=port)r = redis.Redis(connection_pool=pool)r.set('foo', 'bar')print(r.get('foo'))
3.1 string operation
Strings in redis are stored in memory according to a name corresponding to a value.
1. set (name, value, ex = None, px = None, nx = False, xx = False)
Set the value in Redis. default value. If it does not exist, it is created. If it exists, modify the parameter ex, expiration time (in seconds) px, and expiration time (in milliseconds) nx. If it is set to True, the current set operation is executed only when the name does not exist. If it is set to True, the pre-job set operation is executed only when the name exists.
Operation Command
# Set a k-vr.set ('name', 'bigberg ') print (r. get ('name') # Set the expiration time to 2 seconds # obtain the value Noner after 2 seconds. set ('name', 'bigberg ', ex = 2) print (r. get ('name') time. sleep (2) print (r. get ('name '))
2. setnx (name, value)
The setting value. If the name does not exist, perform the setting operation (ADD. if setnx ('name', 'Tom ') is used, the value of name is still 'bigberg' r. setnx ('age', 22) print (r. get ('age '))
3. setex (name, value, time)
# Set Value # parameter: # time, expiration time (Digital seconds or timedelta object)
4. psetex (name, time_ms, value)
# Set Value # parameter: # time_ms, expiration time (number ms or timedelta object)
5. mset (* args, ** kwargs)
Batch setting values such as: mset ({'k1 ': 'v1', 'k2': 'v2'}) r. mset ({'A': 1, 'B': 2}) print (r. get ('A') print (r. get ('B '))
6. get (name)
Get value
7. mget (keys, * args)
Batch retrieval, for example, mget ('ylr ', 'wupeiqi') or r. mget (['ylr ', 'wupeiqi']) r. mset ({'A': 1, 'B': 2}) print (r. mget ('A', 'B '))
8. getset (name, value)
Set a new value and obtain the original value # the original value is returned to print (r. getset ('name', 'Tom ') print (r. get ('name '))
9. getrange (key, start, end)
If it is a Chinese character, in UTF-8 encoding, a Chinese character occupies 3 bytes r. set ('address', 'hangzhou') res = r. getrange ('address', 0, 2) print (res. decode ())
10. setrange (name, offset, value)
# Modify the string content and replace it from the specified string index (if the new value is too long, add it back) # parameter: # offset, string index, byte (one Chinese Character in three bytes) # value: the value r. setrange ('address', 0, 'su') print (r. get ('address '). decode () # output Suzhou r. setrange ('name', 2, 'ol ') print (r. get ('name '). decode () # output Tool # Tom changed to Tool
11. setbit (name, offset, value)
* For example, you can use the most space-saving method to store the number of online users and which users are online.
# Perform operations on bits in the binary representation of the value corresponding to name # parameter: # name, redis name # offset, bit index (convert the value to binary before indexing) # value, the value can only be 1 or 0 # Note: if there is a corresponding in Redis: n1 = "foo", then the binary representation of the string foo is: 01100110 01101111 01101111, if setbit ('n1 ', 7, 1) is executed, 7th bits are set to 1, and the final binary value is 01100111 01101111 01101111, that is: "goo" # Change Tool to Pool # change the ascii value of T to the ASCII value of P print (r. get ('name') r. setbit ('name', 5, 0) print (r. get ('name') # output B 'Tool' B 'Pool'
12. getbit (name, offset)
# Obtain a value (0 or 1) print (r. getbit ('name', 3) in the binary representation of the value corresponding to name # output 1
13. bitcount (key, start = None, end = None)
# Obtain the number of 1 in the binary representation of the value corresponding to name # parameter: # key, Redis name # start, bit start position # end, bit end position print (r. bitcount ('name', 0, 20) # output 18
14. strlen (name)
# Return the byte length of the value corresponding to name (3 bytes for one Chinese character) print (r. strlen ('address') # output 6
15. incr (self, name, amount = 1)
# The value corresponding to the auto-increment name. If the name does not exist, name = amount is created. Otherwise, auto-increment is created. # Parameter: # name, Redis name # amount, auto increment (must be an integer) for I in range (5): print (r. incr ('login _ user') # output 12345
16. incrbyfloat (self, name, amount = 1.0)
# The value corresponding to the auto-increment name. If the name does not exist, name = amount is created. Otherwise, auto-increment is created. # Parameter: # name, Redis name # amount, auto increment (float type) for I in range (5): print (r. incrbyfloat ('num', 1.2) # output 1.22.43.64.86.0
17. decr (self, name, amount = 1)
# The value corresponding to the auto-increment name. If the name does not exist, name = amount is created. Otherwise, the auto-increment value is used. # Parameter: # name, Redis name # amount, auto-subtraction (integer) for I in range (5): print (r. decr ('login _ user') # output 43210
18. append (key, value)
# Append content to the value corresponding to redis name # parameter: key, redis name value, string to append print (r. get ('address '). decode () print (r. append ('address', 'xihu ') print (r. get ('address '). decode () # output: Hangzhou 15 Hangzhou Xihu District