How to use Redis in Python? The following article will introduce to you how to use Redis in Python. I hope it will be helpful to you!
Previously we used Redis
client to use Redis
, but in actual work, in most cases The following are all using Redis
through code. Since the editor is familiar with Python
, we will learn how to use Python
today. ##Redis. [Related recommendations:
Redis video tutorial]
First you need to install it.
is installed (
Python3 is recommended). The
Python
Redis is installed (
pip install redis).
Redis through
Python. Then write a
kv, and finally print out the queried
v.
#!/usr/bin/python3 import redis # 导入redis模块 r = redis.Redis(host='localhost', port=6379, password="pwd@321", decode_responses=True) # host是redis主机,password为认证密码,redis默认端口是6379 r.set('name', 'phyger-from-python-redis') # key是"name" value是"phyger-from-python-redis" 将键值对存入redis缓存 print(r['name']) # 第一种:取出键name对应的值 print(r.get('name')) # 第二种:取出键name对应的值 print(type(r.get('name')))
##getis the last one in the connection pool command to execute.
Connection pool
, a connection will be created, and redis
operations will be performed based on this connection. Release after the operation is completed. Under normal circumstances, this is no problem, but when the amount of concurrency is high, frequent connection creation and release will have a high impact on performance, so the connection pool comes into play. The principle of connection pool: Create multiple connections in advance. When performing
operations, directly obtain the already created connections for operation. After completion, the connection will not be released, but returned to the connection pool for subsequent redis
operations! This avoids continuous creation and release, thus improving performance! <pre class="brush:js;toolbar:false;">#!/usr/bin/python3
import redis,time # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库
pool = redis.ConnectionPool(host=&#39;localhost&#39;, port=6379, password="pwd@321", decode_responses=True) # host是redis主机,需要redis服务端和客户端都起着 redis默认端口是6379
r = redis.Redis(connection_pool=pool)
r.set(&#39;name&#39;, &#39;phyger-from-python-redis&#39;)
print(r[&#39;name&#39;])
print(r.get(&#39;name&#39;)) # 取出键name对应的值
print(type(r.get(&#39;name&#39;)))</pre>
Basic Operation Practice
commands, we take the SET
command as an example to demonstrate.
set(name, value, ex=None, px=None, nx=False, xx=False)
Interpretation | |
---|---|
Expiration time (m)
| |
Expiration time (ms)
| |
If true, only name does not exist
| |
## | If true, the current set operation will only be executed when name exists implement
|
The above is the detailed content of A brief analysis of how to use Redis in Python. For more information, please follow other related articles on the PHP Chinese website!