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 usePython3
).Redis
OfPython
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
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
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
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
Above , You'll find that
name
Ofset
Not in force , becausename
Already exists in the database . andname1
Ofset
Has to take effect , becausename1
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
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
The sidebar is recommended
- Python avatar animation, come and generate your own animation avatar
- leetcode 1884. Egg Drop With 2 Eggs and N Floors(python)
- leetcode 1910. Remove All Occurrences of a Substring(python)
- Python and binary
- First acquaintance with Python class
- [Python data collection] scrapy book acquisition and coding analysis
- Python crawler from introduction to mastery (IV) extracting information from web pages
- Python crawler from entry to mastery (III) implementation of simple crawler
- The apscheduler module in Python implements scheduled tasks
- 1379. Find the same node in the cloned binary tree (Java / C + + / Python)
guess what you like
-
Python connects redis, singleton and thread pool, and resolves problems encountered
-
Python from 0 to 1 (day 11) - Python data application 1
-
Python bisect module
-
Python + OpenGL realizes real-time interactive writing on blocks with B-spline curves
-
Use the properties of Python VTK implicit functions to select and cut data
-
Learn these 10000 passages and become a humorous person in the IT workplace. Python crawler lessons 8-9
-
leetcode 986. Interval List Intersections(python)
-
leetcode 1860. Incremental Memory Leak(python)
-
How to teach yourself Python? How long will it take?
-
Python Matplotlib drawing pie chart
Random recommended
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
- Daily python, Chapter 18, class
- "I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
- Django view
- Python implements filtering emoticons in text
- When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
- Python crawler - get fund change information
- Highlight actor using Python VTK
- Python crawler actual combat: crawling southern weekend news articles
- leetcode 406. Queue Reconstruction by Height(python)
- leetcode 1043. Partition Array for Maximum Sum (python)
- Python * * packaging and unpacking details
- Python realizes weather query function
- Python from 0 to 1 (day 12) - Python data application 2 (STR function)
- Python from 0 to 1 (day 13) - Python data application 3
- Numpy common operations of Python data analysis series Chapter 8
- How to implement mockserver [Python version]
- Van * Python! Write an article and publish the script on multiple platforms
- Python data analysis - file reading
- Python data De duplication and missing value processing
- Python office automation - play with browser
- Python series tutorial 127 -- Reference vs copy
- Control flow in Python: break and continue
- Teach you how to extract tables in PDF with Python
- leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal(python)
- leetcode 1338. Reduce Array Size to The Half(python)
- Object oriented and exception handling in Python
- How to configure load balancing for Django service
- How to embed Python in go
- Python Matplotlib drawing graphics
- Python object-oriented programming 05: concluding summary of classes and objects