pythonRedis 订阅功能实现

两天机器做,host要写订阅主机的ip,客户端发消息,服务端订阅消息

cat redis_connector.py

#!/usr/bin/env python
__author__ = 'Q.Li'
import redis
r = redis.Redis(host='localhost',port=6379,db=0)

#r['YourKey'] = 'YourValue'

cat monitor_server.py

import redis_connector as redis

import pickle

channel = 'monitor_queue'

msg_queue = redis.r.pubsub()

msg_queue.subscribe(channel)

msg_queue.parse_response()

count = 0

while True:

  date = msg_queue.parse_response()

  print  'round %s :: ' % count,pickle.loads(data[2])

  count +=1

一、A:主机操作

1.首先运行redis-server服务

root@ubuntu:/usr/local/src/redis-2.8.17/src# ./redis-server 

2.运行redis-cli

root@ubuntu:/usr/local/src/redis-2.8.17/src# ./redis-cli

127.0.0.1:6379>

3.制定订阅频道号,设定为chan_107

127.0.0.1:6379> help SUBSCRIBE       #订阅使用方法,可以订阅多个频道

SUBSCRIBE channel [channel ...]
summary: Listen for messages published to the given channels
since: 2.0.0
group: pubsub

127.0.0.1:6379> SUBSCRIBE chan_107
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "chan_107"
3) (integer) 1

这样就一直等待接受消息...

B:主机

1.运行python编译器

root@liqian-python:/pythonShare/monitor/m_server/core# python
Python 2.7.10 (default, Oct 14 2015, 16:09:02)
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

>>> import redis_connector as redis,tab

>>> redis.r.publish('chan_107','hello,ubuntu')
1L
>>>

1L就发送成功,chan_107为订阅频道,hello,ubuntu为发送字符

A:主机

1.自动接受消息

1) "message"
2) "chan_107"
3) "hello,ubuntu"

二、循环接受消息,按照上面的案列来实现

在同一台B机器上做的操作

1.再打开一个B终端,进入python交互器,

root@liqian-python:/pythonShare/monitor/m_server/core# python
Python 2.7.10 (default, Oct 14 2015, 16:09:02)
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import redis_connector as redis

>>> msg_q = redis_connector.r.pubsub()

>>> msg_q.subscribe('chan_107')

>>> msg_q.parse_response() #接受消息,

['subscribe', 'chan_107', 1L]

>>> msg_q.parse_response() #需要手动来查看消息,每次执行都查收消息,如果没有消息就会阻塞,会一直等消息。
['message', 'chan_107', 'Hello,world']

原文地址:https://www.cnblogs.com/i1991/p/6287746.html