python-redis订阅者和发布

#发布者:


>>> 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)

 

你可能感兴趣的:(redis)