首页 > 编程语言 > 详细

5、python 操作redis

时间:2021-05-14 21:26:36      阅读:31      评论:0      收藏:0      [点我收藏+]

1、直接操作

import redis
pool=redis.ConnectionPool(host=‘49.234.159.231‘,port=9221,password=‘9U6rQ19kET10iKYa‘)
conn=redis.Redis(connection_pool=pool)
name=conn.get(‘name‘)
print(name)								#输出为b‘nulang‘,二进制格式
conn.set(‘age‘,20)
age=conn.get(‘age‘),
print(age.decode())							#转码后输出为20

2、pub/sub---发布订阅

#订阅,例:
import redis
pool=redis.ConnectionPool(host=‘49.234.159.231‘,port=26379)
conn=redis.Redis(connection_pool=pool)
pub=conn.pubsub()
pub.subscribe(‘+sdown‘,‘-sdown‘)
while True:
    data=pub.parse_response()
    print(data)

3、sentinel

from redis.sentinel import Sentinel
#获取主从节点
sentinel = Sentinel([(‘49.234.159.231‘,26379)],socket_timeout=0.1)
master_ip = sentinel.discover_master(‘mymaster‘)
slave_ip =sentinel.discover_slaves(‘mymaster‘)

#操控master或slave进行读写
master = sentinel.master_for(‘mymaster‘, socket_timeout=0.1)
master.set(‘foo‘,‘bar‘) 					#获取主redis服务器并进行写入
slave = sentinel.slave_for(‘mymaster‘, socket_timeout=0.1)
slave.get(‘foo‘)						#获取从redis服务器进行获取

4、redis与sentinel结合实现failover的变化监控

import redis
from redis.sentinel import Sentinel
sentinel = Sentinel([(‘49.234.159.231‘,26379)],socket_timeout=0.1)

pool=redis.ConnectionPool(host=‘49.234.159.231‘,port=26379)
conn=redis.Redis(connection_pool=pool)
pub=conn.pubsub()
pub.subscribe(‘+sdown‘,‘-sdown‘)
for i in pub.listen():
    if i[‘type‘] == ‘message‘:
        master_ip = sentinel.discover_master(‘mymaster‘)
        slave_ip = sentinel.discover_slaves(‘mymaster‘)
        pool1 = redis.ConnectionPool(host=‘49.234.159.231‘, port=9221, password=‘9U6rQ19kET10iKYa‘)
        conn1=redis.Redis(connection_pool=pool1)
        conn1.set(‘master‘,str(master_ip))
        conn1.set(‘slave‘,str(slave_ip))
        conn1.publish(‘failover‘,‘change‘)

5、python 操作redis

原文:https://www.cnblogs.com/kuangfengnulang/p/14769653.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!