python操作redis叢集
阿新 • • 發佈:2018-11-25
上程式碼
1、對redis的單例項進行連線操作 python3 >>>import redis >>>r = redis.StrictRedis(host='localhost', port=6379, db=0,password='root') >>>r.set('lufei', 'guojialei') True >>>r.get('lufei') 'bar' -------------------- 2、sentinel叢集連線並操作 [[email protected] ~]# redis-server /data/6380/redis.conf [[email protected] ~]# redis-server /data/6381/redis.conf [[email protected] ~]# redis-server /data/6382/redis.conf [[email protected] ~]# redis-sentinel /data/26380/sentinel.conf & -------------------------------- ## 匯入redis sentinel包 >>> from redis.sentinel import Sentinel ##指定sentinel的地址和埠號>>> sentinel = Sentinel([('localhost', 26380)], socket_timeout=0.1) ##測試,獲取以下主庫和從庫的資訊 >>> sentinel.discover_master('mymaster') >>> sentinel.discover_slaves('mymaster') ##配置讀寫分離 #寫節點 >>> master = sentinel.master_for('mymaster', socket_timeout=0.1) #讀節點 >>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1) ###讀寫分離測試 key >>> master.set('oldboy', '123') >>> slave.get('oldboy') '123' ---------------------- redis cluster的連線並操作(python2.7.2以上版本才支援redis cluster,我們選擇的是3.5) https://github.com/Grokzen/redis-py-cluster 3、python連線rediscluster叢集測試 使用 python3 >>> 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 >>> 'bar' ----------------------