python订阅发布者模式_python-redis订阅者和发布

本文演示了如何使用Python的redis库实现订阅发布者模式。通过创建RedisHelper类连接Redis,定义了publish方法用于发布消息,subscribe方法用于订阅频道。在发布者中发布消息,订阅者则可以接收到并打印出来。示例代码展示了如何订阅和发布到名为'monitor'的频道。
摘要由CSDN通过智能技术生成

#发布者:

>>> import redis

>>> rc= redis.Redis()

>>> rc.publish('test01','hello word')

1L

>>> rc.publish('test01','hello words')

1L

#订阅者

>>> import redis

>>> rc= redis.Redis()

>>> ps=rc.pubsub()

>>> ps.subscribe('test01')

>>> ps.listen().next().get('data')

1L

>>> ps.listen().next().get('data')

'hello word'

>>> ps.listen().next().get('data')

'hello words'

首先定义一个RedisHelper类,连接Redis,定义频道为monitor,定义发布(publish)及订阅(subscribe)方法。

#!/usr/bin/env python

#-*- coding:utf-8 -*-

import redis

class RedisHelper(object):

def __init__(self):

self.__conn = redis.Redis(host='192.168.0.110',port=6379)#连接Redis

self.channel = 'monitor' #定义名称

def publish(self,msg):#定义发布方法

self.__conn.publish(self.channel,msg)

return True

def subscribe(self):#定义订阅方法

pub = self.__conn.pubsub()

pub.subscribe(self.channel)

pub.parse_response()

return pub

发布者

#!/usr/bin/env python

# -*- coding:utf-8 -*-

#发布

from RedisHelper import RedisHelper

obj = RedisHelper()

obj.publish('hello')#发布

订阅者

#!/usr/bin/env python

# -*- coding:utf-8 -*-

#订阅

from RedisHelper import RedisHelper

obj = RedisHelper()

redis_sub = obj.subscribe()#调用订阅方法

while True:

msg= redis_sub.parse_response()

print (msg)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值