r = redis.Redis(host='192.168.1.112',port=6379,db=0)
在Python交互器中导入redis_connector,并发布消息:
>>> redis.r.publish('chan_107','hello my name is xpleaf')
1L
此时在Server端中就能看到Client端发布的消息了:
127.0.0.1:6379> SUBSCRIBE chan_107
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "chan_107"
3) (integer) 1
1) "message"
2) "chan_107"
3) "hello my name is xpleaf" 2.方法二:Server端使用Python程序+Client端使用Python交互器 (1)Server端
程序代码如下:
import redis_connector as redis
while True:
data = msg_queue.parse_response() #waiting for the publisher
print data
可以看到这里也导入了redis_connector模块用来连接本地的Redis数据库,跟Client端的类似,只是IP地址改为'localhost',如下:
#!/usr/bin/env python
import redis
r = redis.Redis(host='192.168.1.112',port=6379,db=0)
在Python交互器中导入redis_connector,并发布消息:
>>> redis.r.publish('chan_107','hello my name is yonghaoye')
2L
>>> redis.r.publish('chan_107','second msg')
2L
上面两步其实和方法一是一样的。
此时在Server端中也可以订阅到Client端发布的消息了:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day7/monitor/m_server/core$ python redis_sub.py
['message', 'chan_107', 'hello my name is yonghaoye']
['message', 'chan_107', 'second msg']
===>光标停在此处,继续监听Client端发布的消息 3.方法三:Server端使用Python程序+Client端使用Python程序
直接给出Client端的程序代码:
import redis_connector as redis
for i in range(10):
redis.r.publish('chan_107','This is the NO.%s msg I send to you' % i)
Server端开始监听:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day7/monitor/m_server/core$ python redis_sub.py Client端发布消息:
[root@moban ~]# python publish.py 在Server端中很快就可以监听到Client端发布的消息:
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day7/monitor/m_server/core$ python redis_sub.py
['message', 'chan_107', 'This is the NO.0 msg I send to you']
['message', 'chan_107', 'This is the NO.1 msg I send to you']
['message', 'chan_107', 'This is the NO.2 msg I send to you']
['message', 'chan_107', 'This is the NO.3 msg I send to you']
['message', 'chan_107', 'This is the NO.4 msg I send to you']
['message', 'chan_107', 'This is the NO.5 msg I send to you']
['message', 'chan_107', 'This is the NO.6 msg I send to you']
['message', 'chan_107', 'This is the NO.7 msg I send to you']
['message', 'chan_107', 'This is the NO.8 msg I send to you']
['message', 'chan_107', 'This is the NO.9 msg I send to you']