In each use redis are connected, then would lower the efficiency of redis, knows redis is based on the high memory database, efficiency thief, so every time the connection more than the real use of resources and time consumption. So in order to save resources, reduce the role of multiple connection loss, connection pool serves as a cache multiple clients connected to the redis server when there is a new client to connect when, at this time, just go get a connection pool connection can, in fact, the connection pool is to share a connection to multiple clients, can be said to be broadcast, use, then went to the reception.
#-*-coding:utf-8-*-
import redis
# 连接池连接使用,节省了每次连接用的时间
conn_pool = redis.ConnectionPool(host='localhost',port=6379)
# 第一个客户端访问
re_pool = redis.Redis(connection_pool=conn_pool)
# 第二个客户端访问
re_pool2 = redis.Redis(connection_pool=conn_pool)
# key value存储到redis数据库
try:
re_pool.set('chinese1', 'hello_world')
re_pool2.set('chinese2', 'hello_python')
except Exception as e:
print(e)
# 根据key获取存的数据的内容
data_info = re_pool.get('chinese1')
data_info2 = re_pool.get('chinese2')
# 输出从redis库中取出来的数据的内容
print(data_info)
print(data_info2)
# 获取两个连接的信息
id1 = re_pool.client_list()
id2 = re_pool2.client_list()
# 输出两个连接的id,判断是否一致
print('re_pool_id{}======re_pool2_id{}'.format(id1[0]['id'], id2[0]['id']))
redis redis-MQ queue operation
Redis queue high efficiency, and easy to use.
1.lpush
From left to right insert queue
2.lrange
View the inserted data
Import Redis
Import json
# redis连接
re_queue = redis.Redis(host='localhost', port=6379 )
# 顺序插入五条数据到redis队列,sort参数是用来验证弹出的顺序
num = 0
for i in range(0, 5):
num = num + 1
# params info
params_dict = {"channel":"facebook", "operate":"publish", "sort":num}
# 从左往右入队到redis
re_queue.lpush("params_info", json.dumps(params_dict))
# 查看目标队列数据
result = re_queue.lrange("params_info", 0, 10)
print(result)
# 结果输出
# [b'{"channel": "facebook", "operate": "publish", "sort": 5}', b'{"channel": "facebook", "operate": "publish", "sort": 4}', b'{"channel": "facebook", "operate": "publish", "sort": 3}',
b'{"channel": "facebook", "operate": "publish", "sort": 2}', b'{"channel": "facebook", "operate": "publish", "sort": 1}']
3.rpop
From left to right, the first one into the right most certainly, to deal with the first one, from right to left will pop up
4.rpush,lpop
rpush from right to left into the team, the first one on the far left, lpop pop from the left
5.llen
Returns the length of the list