---
title: "python-redis订阅者和发布"
author: "xwins"
date: "2016-09-15T17:29:35Z"
tags: []
categories: ["移动开发"]
slug: "python-redis"
draft: false
lastmod: "2016-09-15T17:35:28Z"
id: 2324544
url: "https://886.iteye.com/blog/2324544"
---

```
#发布者:


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