python redis tutorial

1. Install redis module package in Python

pip install redis

2. Connect Python to redis

Redis provides two classes: redis and StrictRedis. StrictRedis is used to implement most official commands. Redis is a subclass of StrictRedis, which is used to use the old version backward.
The result retrieved by redis defaults to bytes. We can set decode_ Change responses = true to a string.

import redis

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

r = redis.StrictRedis(host=host,port=port,db=0)
key = r.keys()
print(key)

r = redis.StrictRedis(host=host,port=port,db=0,decode_responses=True)
key = r.keys()
print(key)

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 establish a connection pool and use it as a parameter Redis, so that multiple Redis instances can share a connection pool.

import redis

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

key = r.keys()
print(key)

3. redis basic command - string

3.1 set(name, value, ex=None, px=None, nx=False, xx=False)

Set the value in Redis by default. If it does not exist, it will be created, and if it exists, it will be modified.

Parameters:

  • ex - expiration time (seconds)
  • px - expiration time (MS)
  • nx - if set to True, the current set operation will be executed only if name does not exist
  • xx - if set to True, the current set operation will be executed only when name exists

ex - expiration time (seconds). Here, the expiration time is 3 seconds. After 3 seconds, the value of key test becomes None

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

r.set('test','123456',ex=3)  # Set the value of the key test to 123456 and the expiration time to 3 seconds
print("test The value of is:{}".format(r.get('test')))

time.sleep(3)
print("3 Seconds later test The value of is:{}".format(r.get('test')))


px - expiration time (haos). Here, the expiration time is 3 haos. After 3 milliseconds, the value of foo will become None

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

r.set('test','1234',px=3)  # Set the value of the key test to 1234 and the expiration time to 3 milliseconds
print("test The value of is:{}".format(r.get('test')))

time.sleep(0.003)
print("3 Millisecond later test The value of is:{}".format(r.get('test')))


nx - if set to True, the current set operation will be executed (New) only if name does not exist

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("The keys that exist in the current database are:{}".format(r.keys()))
print("if test If the key does not exist, it is set test The value of is 123456, otherwise it will not be executed")
r.set('test','123456',nx=True)  # When the test key does not exist, set the value of the key test to 123456
print("test The value of is:{}".format(r.get('test')))


xx - if set to True, the current set operation will be executed (modified) only if name exists

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or redis StrictRedis

print("The keys that exist in the current database are:{}".format(r.keys()))
print("if test If the key exists, modify it test The value of is 123456, otherwise it will not be executed")
r.set('test','123456',xx=True)  # When the test key exists, the value of the modify key test is 123456
print("test The value of is:{}".format(r.get('test')))

3.2 setnx(name, value)

Set the value. Only when name does not exist, perform the setting operation (add)

3.3 setex(name, time, value)

Set value, time - expiration time (numeric seconds or timedelta object)

3.4 psetex(name, time_ms, value)

Set value, time_ms - expiration time (numeric milliseconds or timedelta object)

3.5 mset and mget

  • mset(*args, **kwargs): batch setting value
  • mget(keys, *args): get values in batch
import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("The keys that exist in the current database are:{}".format(r.keys()))

print("Set key k1 and k2 The values of are v1 and v2")
r.mset({'k1': 'v1', 'k2': 'v2'})
print("Get key k1 and k2 Value of")
print(r.mget("k1", "k2"))   # Take out the values corresponding to multiple keys at one time

3.6 getset(name, value)

Set the new value and get the original value

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("The keys that exist in the current database are:{}".format(r.keys()))

print("Get key test The value of is:{}".format(r.get('test')))

result = r.getset('test','12345')  # Set the new value of key test to 12345 and return the value of original test to 1234
print("key test The original value of is:{}".format(result))
print("Get key test The current value of is:{}".format(r.get('test')))

3.7 getrange(key, start, end)

Get subsequence (according to index and byte). One Chinese character takes up 3 bytes

Parameters:

  • Start - start position (start index starts from 0)
  • End - end position
import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("The keys that exist in the current database are:{}".format(r.keys()))
print("Get key test The value of is:{}".format(r.get('test')))

result = r.getrange('test',0,1)  # Get subsequence of indexes 0 to 1
print("key test The subsequences from 0 to 1 of are:{}".format(result))

result = r.getrange('test',1,4)  # Gets the subsequence of indexes 1 through 4
print("key test The subsequences from 1 to 4 of are:{}".format(result))

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("The key currently exists in the database:{}".format(r.keys()))
print("Get key name The value of is:{}".format(r.get('name')))

result = r.getrange('name',0,2)  # Get subsequence of indexes 0 to 2
print("key name The subsequences from 0 to 2 of are:{}".format(result))

result = r.getrange('name',3,20)  # Gets the subsequence of indexes 3 through 20
print("key name The subsequences of 3 to 20 are:{}".format(result))


Note: one Chinese character takes up 3 bytes. If the subsequence from 0 to 1 is taken, an error will be reported (less than one Chinese character)

3.8 setrange(name, offset, value)

Modify the string content and replace it backward from the specified string index (if the new value is too long, it will be added backward)

Parameters:

  • offset - index of the string, bytes (three bytes for one Chinese character)
  • Value - the value to set
import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("The keys that exist in the current database are:{}".format(r.keys()))
print("Get key name The value of is:{}".format(r.get('name')))

print('take name The value starting from the first byte of is changed to "I", accounting for 3 bytes')
r.setrange('name',0,'I')  # 
print("key name Change the value of to:{}".format(r.get('name')))

3.9 strlen(name)

Returns the byte length of the corresponding value of name (3 bytes for a Chinese character)

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("Get key test The value of is:{}".format(r.get('test')))
result = r.strlen('test')
print("key test The byte length of is:{}".format(result))

print("Get key name The value of is:{}".format(r.get('name')))
result = r.strlen('name')
print("key name The byte length of is:{}".format(result))

3.10 incr(key, amount=1)

Auto increment the value corresponding to the key. When the key does not exist, create key = amount; otherwise, auto increment.

Parameter: amount - self increment (must be an integer)

import redis
import time

host = '192.168.149.153' # redis service address
port = 6379  # redis service port

pool = redis.ConnectionPool(host=host,port=port,db=0,decode_responses=True)
r = redis.Redis(connection_pool=pool) # Or use redis StrictRedis

print("Get key num The value of is:{}".format(r.get('num')))
print("Get key num1 The value of is:{}".format(r.get('num1')))

print("Will key num The value of is increased by 1")
r.incr('num',amount=1)
print("Get key num The current value is:{}".format(r.get('num')))

r.incr('num1',amount=10)
print("Get key num1 The current value is:{}".format(r.get('num1')))

3.11 decr(key, amount=1)

Automatically subtract the value corresponding to the key. When the key does not exist, create name = amount; otherwise, automatically subtract.

Parameter: amount - self subtraction (integer)

3.12 append(key, value)

Append content after the value corresponding to the key

Parameter: value - string to append

4. redis basic command hash

Keywords: Python Redis

Added by landung on Thu, 10 Feb 2022 23:37:20 +0200