下载老版本客户端:
wget https://pypi.python.org/packages/source/r/redis/redis-2.10.1.tar.gz --no-check-certificate
解压并安装:
tar zxf redis-2.10.1.tar.gz && cd redis-2.10.1 && python setup.py install
编辑py文件:
vim olda.py
import redis
r = redis.Redis(host='localhost',port=6379,password='redhat',db=0)
r.set('name','olda')
print r.get('name')
执行:
python olda.py
# 输出redhat
redhat
新版更新连接方法(普通式):
下载py包:
wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
解压进入目录:
tar xf Python-3.6.3.tar.xz && cd Python-3.6.3
编译:
./configure && make && make install && echo $?
下载redis-py程序:
wget https://github.com/andymccurdy/redis-py/archive/master.zip
安装redis-py库:
unzip master.zip && cd redis-py-master/
python3 setup.py install && echo $? && cd ..
连接单节点:
vim olda.py
import redis
r = redis.StrictRedis(host='localhost',port=6379,db=0,password='redhat')
r.set('name','olda')
print(r.get('name'))
执行脚本:
python3 olda.py
b'olda'
连接哨兵集群:
vim olda.py
# 导入redis sentinel库
from redis.sentinel import Sentinel
# 实例化sentinel对象
sentinel = Sentinel([('localhost',26380)],socket_timeout=0.1)
# 获取主库信息
print(sentinel.discover_master('mymaster'))
# 获取从库信息
print(sentinel.discover_slaves('mymaster'))
# 配置写节点
master = sentinel.master_for('mymaster',socket_timeout=0.1,password='redhat')
# 配置从节点
slave = sentinel.slave_for('mymaster',socket_timeout=0.1,password='redhat')
# 读写分离测试(字符串拼接)
print('master-mode:',master.set('name','olda'))
print('slave-node:',slave.get('name'))
执行脚本:
python3 olda.py
('10.0.0.10', 6380)
[('10.0.0.10', 6382), ('10.0.0.10', 6381)]
master-mode: True
slave-node: b'olda'
新版更新连接方法(分布式):
下载py包:
wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
解压进入目录:
tar xf Python-3.6.3.tar.xz && cd Python-3.6.3
编译:
./configure && make && make install && echo $?
下载redis-py-cluster程序:
wget https://github.com/Grokzen/redis-py-cluster/archive/unstable.zip
安装redis-py-cluster:
unzip unstable.zip && cd redis-py-cluster-unstable
python3 setup.py install && echo $? && cd ..
连接分布式集群:
vim olda.py
# 导入redis cluster库
from rediscluster import StrictRedisCluster
# 定义地址变量
startup_nodes = [{'host':'127.0.0.1','port':'7000'}]
# 实例化cluster对象
rc = StrictRedisCluster(startup_nodes=startup_nodes,decode_responses=True)
# 写入数据
print(rc.set('name','olda'))
# 读取数据
print(rc.get('name'))
执行脚本:
python3 olda.py
True
olda