首页 » Python » Redis订阅&发布以及python代码实现

Redis订阅&发布以及python代码实现

2015-12-31 16:10:05阅读(282)

A:命令行
服务器端
192.168.1.168:7000>subscribefoo bar
Readingmessages...(pressCtrl-Ctoquit)
1)"subscribe"
2)"RedisChat"
3)(integer)1
1
1)"message"
2)"redisChat"
3)"hello!"
1)"message"
2)"redisChat"
3)"mynameisalex!"

客户端
127.0.0.1:7000>publishfoo"hello!"
(integer)1
127.0.0.1:7000>publishbar"mynameisalex!"
(integer)1
127.0.0.1:7000>publishbar"我是中文!"
(integer)1
127.0.0.1:7000>

B:集群python
pip install redis-py-cluster
---------------------------------------------------------------
服务器端
from rediscluster import StrictRedisCluster
startup_nodes = [{"host": "192.168.1.168", "port": "7000"}]
rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
ps=rc.pubsub()
ps.subscribe(['foo', 'bar'])
for item in ps.listen():
if item['type'] == 'message':
print item['data']
客户端
from rediscluster import StrictRedisCluster
startup_nodes = [{"host": "192.168.1.168", "port": "7000"}]
rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
ps = rc.pubsub()
ps.subscribe(['foo', 'bar'])
rc.publish('foo', 'hello foo')
rc.publish('bar', 'hello bar')


C:非集群python
pip install redis
-------------------------------------------------------------
import redis
rc = redis.Redis(host='127.0.0.1')
ps = rc.pubsub()
ps.subscribe(['foo', 'bar'])
for item in ps.listen():
if item['type'] == 'message':
print item['data']

import redis
rc = redis.Redis(host='127.0.0.1')
ps = rc.pubsub()
ps.subscribe(['foo', 'bar'])
rc.publish('foo', 'hello foo')
rc.publish('bar', 'hello bar')

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹