连接单个节点
单个的直接导入redis模块,设置ip,密码,端口,直接连就OK了
#python 2.7.x
#redis (2.10.6)
import redis
def connRedis():
pool=redis.ConnectionPool(host='ip',password='password',port=port)
r=redis.Redis(connection_pool=pool)
# r=redis.StrictRedis(connection_pool=pool)
r.set("name","caoji")
print(r.get('name'))
connRedis()
连接集群
redis_nodes里面的ip和端口根据实际情况设置,如果你的集群有公网IP就直接设置为公网ip就可以了
和网上的大同小异,只是注意如果你的集群设置了auth,那么StrictRedisCluster里面就要补上密码,否则连接不上集群
#python2.7.x
#redis-2.10.6
#redis-py-cluster (1.3.6)
from rediscluster import StrictRedisCluster
import sys
def redis_cluster():
redis_nodes = [{'host':'127.0.0.1','port':7000},
{'host':'127.0.0.1','port':7001},
{'host':'127.0.0.1','port':7002},
{'host':'127.0.0.1','port':7003},
{'host':'127.0.0.1','port':7004},
{'host':'127.0.0.1','port':7005}
]
try:
redisconn = StrictRedisCluster(startup_nodes=redis_nodes,password='passwd123')
except Exception,e:
print(e)
sys.exit(1)
redisconn.set('name','caonima')
print "name value is:", redisconn.get('name')
redis_cluster()