First, the introduction of Redis
Redis is one of the industry's leading key-value NoSQL databases. 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.
Second, the advantages of Redis
Unusually fast: Redis is very fast and can perform approximately 110000 setup operations per second, and 81,000 per second read operations.
Support for rich data types: Redis support most developers already know data types such as lists, collections, sortable collections, hashes, and so on. This makes it easy to solve a variety of problems in your application because we know which issues to work with which data types are better addressed.
Operations are atomic: All Redis operations are atomic, ensuring that when two customers access the Redis server at the same time, the updated values (the latest value) are obtained.
- Multiutility Tools: Redis is a multifunctional utility that can be used in many such as: cache, Message delivery queue (Redis native support publish/subscribe), in applications such as: Web application sessions, website page hits, etc. any short data
Third, the Redis API uses
The use of Redis-py APIs can be categorized as:
- Connection mode
- Connection pool
- Operation
- String manipulation
- Hash operation
- List operation
- Set operation
- Sort Set operation
- Pipeline
- Publish a subscription
3.1 Connection mode
1. Operating 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, Used for backwards compatibility with older versions 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 pooling
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.
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 manipulation
The string in Redis is stored in memory by a name corresponding to a value.
1.set (name, value, Ex=none, Px=none, Nx=false, Xx=false)
Set the value in Redis, default, create without, modify parameter if present: ex, expiry time (seconds) px, Expiration Time (msec) NX, if set to true, the current set operation executes XX only if name does not exist. If set to true, the pre-post set operation is performed only if name exists
Action commands
# Set a k-vr.set (' name ', ' Bigberg ') print (R.get (' name ')) #设置过期时间为2秒 # after 2 seconds to get the value for Noner.set (' name ', ' Bigberg ', ex=2) print ( R.get (' name ')) Time.sleep (2) Print (R.get (' name '))
2. SETNX (name, value)
Set the value, execute the Set action (add) if R.setnx (' name ', ' Tom ') is the value of ' Bigberg ' r.setnx (' age ', ' print ') (R.get (' time ')) if the name does not exist.
3. Setex (name, value, time)
# set the value # parameter: # time, expiration (number of seconds or Timedelta object)
4. Psetex (name, Time_ms, value)
# set the value # parameter: # Time_ms, Expiration time (numeric milliseconds 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 ') ') (R.get (' B '))
6. Get (name)
Get value
7. Mget (keys, *args)
Bulk gain such as: mget (' ylr ', ' Wupeiqi ') or r.mget ([' Ylr ', ' Wupeiqi ']) r.mset ({' A ': 1, ' B ': 2}) Print (R.mget (' A ', ' B '))
8. Getset (name, value)
Setting a new value and getting the original value # will return the original value to print (R.getset (' name ', ' Tom ')) print (R.get (' name '))
9. GetRange (Key, start, end)
If it is a Chinese character, under Utf-8 encoding, a Chinese character takes up 3 bytes r.set (' address ', ' hangzhou ') res = r.getrange (' address ', 0, 2) print (Res.decode ())
SETRANGE (name, offset, value)
# Modify string contents, start backward replacement from the specified string index (add back if the new value is too long) # parameter: # Offset, string index, byte (three bytes for a kanji) # value, to set the value of R.setrange (' address ', 0, ' Sue ') print (R.get (' address '). Decode ()) # Output Suzhou r.setrange (' name ', 2, ' ol ') print (R.get (' name '). Decode ()) # Output Tool # Tom has become a Tool.
Setbit (name, offset, value)
* Examples of use, in the most space-saving way, the number of online users and which users are online
# operation on binary representation of name corresponding value # parameter: # Name,redis name # offset, bit index (convert value to binary and then index) # value can only be 1 or 0 # Note: If you are in Redis There is a corresponding: N1 = "foo", then the binary representation of String Foo is: 01100110 01101111 01101111 So, if you execute Setbit (' N1 ', 7, 1), the 7th bit is set to 1, Then the final binary becomes 01100111 01101111 01101111, that is: "Goo" #我们将Tool changed to pool#, you need to change the ASCII value of T to P's ASCII value print (r.get (' name ')) R.setbit (' Name ', 5, 0) print (r.get (' name ')) # output B ' Tool ' B ' Pool '
Getbit (name, offset)
# Gets the value of name corresponding to the value of a bit in the binary representation (0 or 1) of print (R.getbit (' name ', 3)) # output 1
Bitcount (Key, Start=none, End=none)
# Gets the value of name corresponding to the number of 1 in the binary representation # parameter: # Key,redis name # start, bit start position # end, bit end position print (R.bitcount (' name ', 0, 20) #) # Output 18
strlen (name)
# returns the byte length of name corresponding value (one kanji 3 bytes) print (R.strlen (' address ')) # output 6
INCR (self, name, amount=1)
# self-increment name corresponding to the value, when the name does not exist, then create Name=amount, otherwise, the self-increment. # parameter: # Name,redis name # amount, self increment (must be integer) for I in range (5): print (R.INCR (' Login_user ')) #输出12345
Incrbyfloat (self, name, amount=1.0)
# self-increment name corresponding to the value, when the name does not exist, then create Name=amount, otherwise, the self-increment. # parameter: # Name,redis name # amount, self-increment (float) for I in range (5): print (r.incrbyfloat (' num ', 1.2)) # Output 1.22.43.64.86.0
DECR (self, name, amount=1)
# self-Subtract the value of name, when name does not exist, create name=amount, otherwise, subtract. # parameter: # Name,redis name # amount, self-meiosis (integer) for I in range (5): print (R.DECR (' Login_user ')) # output 43210
Append (key, value)
# append content after Redis name Value # parameter: key, Redis name value, string to append print (R.get (' address '). Decode ()) print (r.append (' Address ', ' West L. District ') Print (R.get (' address '). Decode ()) # output Hangzhou 15 Xihu District, Hangzhou
Python Introduction to using Redis