current position:Home>Python uses redis

Python uses redis

2022-02-01 03:33:57 Python Institute

「 This is my participation 11 The fourth of the yuegengwen challenge 20 God , Check out the activity details :2021 One last more challenge 」.

Preface

We all use Redis The client to Redis For use , But in practice , In most cases, we use it through code Redis Of , Because Xiaobian is right Python Familiar with , So let's learn how to use Python To operate Redis.

Environmental preparation

  • Redis First you need to install .
  • Python Install well ( It is recommended to use Python3).
  • Redis Of Python Library installed (pip install redis).

Start practicing

A profound

example : We plan to pass Python Connect to Redis. Then write a kv, Finally, we will find v Print out .

Direct connection

#!/usr/bin/python3

import redis   #  Import redis modular 

r = redis.Redis(host='localhost', port=6379, password="[email protected]", decode_responses=True)   # host yes redis host ,password For authentication password ,redis The default port is 6379
r.set('name', 'phyger-from-python-redis')  # key yes "name" value yes "phyger-from-python-redis"  Store key value pairs redis cache 
print(r['name'])  #  The first one is : Remove key name Corresponding value 
print(r.get('name'))  #  The second kind : Remove key name Corresponding value 
print(type(r.get('name')))
 Copy code 

 Execution results

 The server checks the list of clients

Among them get The last command executed for the connection pool .

Connection pool

Usually , Connection required redis when , Will create a connection , Based on this connection redis operation , Release... After the operation is completed . Under normal circumstances , There is no problem with that , But in the case of high concurrency , Frequent connection creation and release will have a higher impact on the performance , So the connection pool works .

The principle of connection pool : Create multiple connections in advance , When doing redis In operation , Directly obtain the created connection for operation . After completion , This connection will not be released , Instead, let it return to the connection pool , Used in subsequent redis operation ! This avoids continuous creation and release , This improves performance !

#!/usr/bin/python3

import redis,time   #  Import redis modular , adopt python operation redis  You can also directly redis The server operation cache database of the host 

pool = redis.ConnectionPool(host='localhost', port=6379, password="[email protected]", decode_responses=True)   # host yes redis host , need redis Both the server and the client are up  redis The default port is 6379
r = redis.Redis(connection_pool=pool)
r.set('name', 'phyger-from-python-redis')
print(r['name'])
print(r.get('name'))  #  Remove key name Corresponding value 
print(type(r.get('name')))
 Copy code 

 Execution results

You'll find that , In actual use, the effect of direct connection and connection pool is the same , It's just that there are obvious differences in high concurrency .

Basic practice

For many Redis command , We are here to SET Command as an example .

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

stay redis-py in set Arguments to the command :

Parameter name paraphrase
ex <int> Expiration time (m)
px <int> Expiration time (ms)
nx <bool> If it is true , only name When there is no , At present set Operation before execution
xx <bool> If it is true , only name In existence , At present set Operation before execution

ex

We plan to create a kv And set it ex by 3, expect 3 This in seconds k Of v Will turn into None.

#!/usr/bin/python3

import redis,time   #  Import redis modular , adopt python operation redis  You can also directly redis The server operation cache database of the host 

pool = redis.ConnectionPool(host='localhost', port=6379, password="[email protected]", decode_responses=True)   # host yes redis host , need redis Both the server and the client are up  redis The default port is 6379
r = redis.Redis(connection_pool=pool)
r.set('name', 'phyger-from-python-redis',ex=3)
print(r['name'])    #  Ought to have v
time.sleep(3)
print(r.get('name'))  #  There should be no v
print(type(r.get('name')))
 Copy code 

3 Seconds expired

nx

because px The unit is too short , We won't do a demonstration , Effect and ex identical .

We plan to repeat set The front has set Yes name, If nothing else , stay nx To true , We will set Failure . But if people set There is no the name1, Will be successful .

#!/usr/bin/python3

import redis,time   #  Import redis modular , adopt python operation redis  You can also directly redis The server operation cache database of the host 

pool = redis.ConnectionPool(host='localhost', port=6379, password="[email protected]", decode_responses=True)   # host yes redis host , need redis Both the server and the client are up  redis The default port is 6379
r = redis.Redis(connection_pool=pool)
r.set('name', 'phyger-0',nx=3) # set Failure 
print(r['name'])    #  Should not take effect 
r.set('name1', 'phyger-1',nx=3) # set success 
print(r.get('name1'))  #  Should take effect 
print(type(r.get('name')))
 Copy code 

 Only non-existent k Will be set

Above , You'll find that name Of set Not in force , because name Already exists in the database . and name1 Of set Has to take effect , because name1 It doesn't exist in the database before .

xx

We plan to repeat set The front has set Yes name, If nothing else , stay nx To true , We will set success . But if people set There is no the name2, It will fail .

#!/usr/bin/python3

import redis,time   #  Import redis modular , adopt python operation redis  You can also directly redis The server operation cache database of the host 

pool = redis.ConnectionPool(host='localhost', port=6379, password="[email protected]", decode_responses=True)   # host yes redis host , need redis Both the server and the client are up  redis The default port is 6379
r = redis.Redis(connection_pool=pool)
r.set('name', 'phyger-0',xx=3) # set Failure 
print(r['name'])    #  It should have changed 
r.set('name2', 'phyger-1',xx=3) # set success 
print(r.get('name2'))  #  There should be no set success 
print(type(r.get('name')))
 Copy code 

 Only exist k Will be set

above , That's all for today , For more information, please refer to redis Official documents .

copyright notice
author[Python Institute],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202010333554381.html

Random recommended