公司项目有个新需求,需要使用redis的消息订阅/发布模式进行数据传输,
需求 : redis版本2.8.8,python 版本2.7.3,redis使用哨兵模式进行连接
下面记录下具体的实现,python环境的搭建就不具体描述了
首先: 采用的连接方式是 哨兵模式
sentinel = Sentinel([('127.0.0.1', 26379), ('127.0.0.2', 26379), ('127.0.0.3', 26379)], socket_timeout=0.5)
# 获取主服务器地址,discover_master 参数为自己的mastername
master = sentinel.discover_master('mymaster')
master的类型为 master: Tuple[Any, Any] ,我们打印下master的值
('127.0.0.1', 6379)
可以看到master的地址为 127.0.0.1,端口号为 6379
那么我们可以采用两种方式进行连接
第一:获取master的ip和端口号进行连接
第二:采用哨兵模式进行连接
具体看下面封装的结构
然后: 封装redishelper,传入参数为
# 将参数修改为自己订阅的参数
# 哨兵地址
sentinel: [('27.0.0.1', 26379), ('127.0.0.2', 26379), ('127.0.0.3', 26379)]
# mastername
master_name: 'mymaster'
# 订阅号
channel: 'mychannel'
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import redis
from redis.sentinel import Sentinel
class RedisHelper:
def __init__(self, sentinel, master_name, channel):
sentinel_conn = Sentinel(sentinel, socket_timeout=0.5)
# 连接方式1,建立连接后,获取主节点的ip和端口号,然后重新采用标准连接(不推荐)
# master = sentinel_conn.discover_master(master_name)
# self.conn = redis.Redis(host=master[0], port=master[1], decode_responses=True)
#连接方式2,直接使用哨兵连接方式连接
master = sentinel_conn.master_for(master_name, socket_timeout=0.5)
self.conn = master
# 加入频道
self.chan_sub = channel
self.chan_pub = channel
def public(self, msg):
self.conn.publish(self.chan_pub, msg) # 开始发布消息
return True
def subscribe(self):
pub = self.conn.pubsub() # 开始订阅
pub.subscribe(self.chan_sub) # 订阅频道
pub.parse_response() # 准备接收
return pub
最后: 使用方式
# 发布消息
obi = RedisHelper(redisIp, master, channel)
obi.public(customers)
可以使用redis-cli来看下是否成功:redis-cli -h redis的masterip subscribe 频道名xxx