一、redis的python客户端
去redis的官网看了一下http://redis.io/clients#python,python的客户端如下:
所以按照经验,已经相关的文章推荐,我选取redis-py作为实验目标。
redis-py的官网是:https://github.com/andymccurdy/redis-py
二、python环境升级
简单了解了一下,redis-py需要python的版本为2.7,linux服务器上自带的是2.6.6或者更低的版本,所以这里要涉及到了版本升级问题(2.6.6->2.7)
搜索了一下,找到这篇文章:Centos 6.4 python 2.6 升级到 2.7
查看python的版本
#python -V
Python 2.6.6
1.下载Python-2.7.3
wget http://python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2
./configure
make all
make install
make clean
make distclean
mv /usr/bin/python /usr/bin/python2.6.6
ln -s /usr/local/bin/python2.7 /usr/bin/python
7.重新检验Python 版本
#vi /usr/bin/yum
将文件头部的
#!/usr/bin/python
改成
#!/usr/bin/python2.6.6
三、PIP安装
1. 前言
pip install redis
or alternatively (you really should be using pip though):
easy_install redis
or from source:
python setup.py install
2. 安装:
(1)下载setuptools包
wget "http://pypi.python.org/packages/source/s/setuptools/setuptools-2.0.tar.gz" --no-check-certificate
(2)解压setuptools包
tar zxvf setuptools-2.0.tar.gz
cd setuptools-2.0
(3)编译setuptools
python setup.py build
(4)开始执行setuptools安装
# python setup.py install
(1) wget "https://pypi.python.org/packages/source/p/pip/pip-1.4.1.tar.gz" --no-check-certificate
(2) tar -xvf pip-1.4.1.tar.gz
(3) cd pip-1.4.1/
(4) python setup.py install
四、安装redis-py
pip install redis
五、使用redis-py操作redis
1. 单机模式
import redis
client = redis.StrictRedis(host='127.0.0.1', port=6379)
key = "hello"
client.set(key, "python-redis")
value = client.get(key)
print "key:" + key + ", value:" + value
key:hello, value:python-redis
2. sentinel模式
>>> from redis.sentinel import Sentinel
>>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
>>> sentinel.discover_master('mymaster')
('127.0.0.1', 6379)
>>> sentinel.discover_slaves('mymaster')
[('127.0.0.1', 6380)]
>>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
>>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
>>> master.set('foo', 'bar')
>>> slave.get('foo')
'bar'
3. cluster模式

$ pip install redis-py-cluster
or from source
$ python setup.py install
>>> from rediscluster import StrictRedisCluster
>>> startup_nodes = [{"host": "127.0.0.1", "port": "7000"}]
>>> # Note: decode_responses must be set to True when used with python3
>>> rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
>>> rc.set("foo", "bar")
True
>>> print(rc.get("foo"))
'bar'