Redis訂閱&釋出以及python程式碼實現
阿新 • • 發佈:2018-11-19
A:命令列
伺服器端
192.168.1.168:7000> subscribe foo bar
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1
1
1) "message"
2) "redisChat"
3) "hello!"
1) "message"
2) "redisChat"
3) "my name is alex!"
客戶端 127.0.0.1:7000> publish foo "hello!" (integer) 1 127.0.0.1:7000> publish bar "my name is alex!" (integer) 1 127.0.0.1:7000> publish bar "我是中文!" (integer) 1 127.0.0.1:7000>
B:叢集Python pip install redis-py-cluster
--------------------------------------------------------------- 伺服器端
-------------------------------------------------------------
客戶端 127.0.0.1:7000> publish foo "hello!" (integer) 1 127.0.0.1:7000> publish bar "my name is alex!" (integer) 1 127.0.0.1:7000> publish bar "我是中文!" (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')