安裝redis-py
pip3 install redis

image
python 操作 redis
默認(rèn)情況下,所有響應(yīng)在Python 3中以字節(jié)返回(輸出打印 type 為 bytes),在Python 2中以str返回。用戶負(fù)責(zé)解碼為Python 3字符串或Python 2 unicode對(duì)象。

image
import redis
#連接 redis
#指定主機(jī)地址,port與服務(wù)器連接,redis默認(rèn)數(shù)據(jù)庫有16個(gè),默認(rèn)db是0
r = redis.Redis(host='172.17.0.4',port=6380,db=0) #password='**'
print(r.get('foo'))
r.set('foo','[1,2,3]')
print(r.get('foo'))
print(r.keys())
r.delete('foo')
print(r.keys())

image
python 連接 redis 使用連接池
redis-py使用connection pool來管理對(duì)一個(gè)redis server的所有連接,避免每次建立、釋放連接的開銷。默認(rèn),每個(gè)Redis實(shí)例都會(huì)維護(hù)一個(gè)自己的連接池??梢灾苯咏⒁粋€(gè)連接池,然后作為參數(shù)Redis,這樣就可以實(shí)現(xiàn)多個(gè)Redis實(shí)例共享一個(gè)連接池
import redis
pool = redis.ConnectionPool(host='172.17.0.4', port=6380)
r = redis.Redis(connection_pool=pool)
r.set('foo', 'Bar')
print(r.get('foo'))
python 連接 redis 主從服務(wù)器 sentinel 集群 (哨兵模式)

image
import redis
from redis.sentinel import Sentinel
#連接哨兵服務(wù)器(主機(jī)名也可以用域名)
sentinel = Sentinel([('172.17.0.4',26379),('172.17.0.4',26380),('172.17.0.4',26381)],socket_timeout=0.5)
# 獲取主服務(wù)器地址
master = sentinel.discover_master('mymaster') # 設(shè)置的master名字
print(master)
# 獲取從服務(wù)器地址
slave = sentinel.discover_slaves('mymaster')
print(slave)
# 獲取主服務(wù)器進(jìn)行寫入
master = sentinel.master_for('mymaster', socket_timeout=0.5, db=0)
print("主服務(wù)器插入前的name為:",master.get('name'))
w_ret = master.set('name', 'shark')
print("主服務(wù)器插入后的name為:", master.get('name'))
# # 獲取從服務(wù)器進(jìn)行讀取(默認(rèn)是round-roubin)
slave = sentinel.slave_for('mymaster', socket_timeout=0.5, db=0)
r_ret = slave.get('name')
print("從服務(wù)器的name為:", r_ret)

image
會(huì)出現(xiàn)如下報(bào)錯(cuò)

image
解決方案: 配置文件中寫入
bind 0.0.0.0
daemonize no
protected-mode no

image
解決方案: 配置文件中
sentinel monitor mymaster 127.0.0.1 6380 2
改成
sentinel monitor mymaster 172.17.0.4 6380 2
python 操作 redis 集群
啟動(dòng)集群
redis-server /etc/redis/7001.conf
redis-server /etc/redis/7002.conf
redis-server /etc/redis/7003.conf
redis-server /etc/redis/7004.conf
redis-server /etc/redis/7005.conf
redis-server /etc/redis/7006.conf

image

image
pip3 install redis-py-cluster
#python連接rediscluster集群測(cè)試
from rediscluster import StrictRedisCluster
startup_nodes = [{"host": "172.17.0.3", "port": "7001"},
{"host": "172.17.0.3", "port": "7002"},
{"host": "172.17.0.3", "port": "7003"},
{"host": "172.17.0.3", "port": "7004"},
{"host": "172.17.0.3", "port": "7005"},
{"host": "172.17.0.3", "port": "7006"} ]
# Note: 與python3一起使用時(shí),decode_responses必須設(shè)置為True
m1 = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
m1.set("name", "shark")
print("集群中的 name 為:",m1.get("name"))
打印結(jié)果如下:

image
可能有報(bào)錯(cuò)如下

image
原因是 rediscluster 和 redis-py 版本不兼容
建議使用以下版本

image