Subscribers can subscribe to one or more channels, and after the publisher sends a message to one channel, all subscribers subscribing to the channel will receive the message, and the Publisher will receive a value that is the number of subscribers who receive the message. A subscriber can only receive a message from a publisher after it has started a subscription, and it is not possible to receive a message before it is released.
Next, give the subscriber's code first
# coding=utf-8
' Created on
2015-9-9
@author: Kwsy ' '
import Redis
Pool=redis. ConnectionPool (host= ' 192.168.1.149 ', port=6379,db=1)
r = Redis. Strictredis (connection_pool=pool)
p = r.pubsub ()
p.subscribe (' Excelfile ') for
item in P.listen ():
Print item
If item[' type '] = = ' message ':
data =item[' data ']
r.set (' s ',)
print data
if item [' Data ']== ' over ': Break
;
P.unsubscribe (' spub ')
print ' unsubscribe '
At runtime, be careful to check the type, once listen, you will receive a message, but not the publisher's message, but the system is sent, the content is {' pattern ': None, ' type ': ' Subscribe ', ' Channel ': ' Spub ', ' Data ': 1L}, this means that you subscribe successfully, the channel is Spub, currently, there is a subscriber.
Then look at the code at the end of the release
# coding=utf-8
' Created on
2015-9-9
@author: Administrator ' '
import Redis
Pool=redis. ConnectionPool (host= ' 192.168.1.142 ', port=6379,db=0)
r = Redis. Strictredis (Connection_pool=pool) while
True:
input = Raw_input ("Publish:")
if input = = ' over ':
print ' Stop publishing ' break
;
R.publish (' spub ', input)
Rwa_input receives user input data to the channel, and the subscriber prints the data after receiving it
Here is a small case to indicate, in actual operation, if you enter is a man, then print out may be garbled, but in fact, not really programming garbled, but when you use CMD command window running, cmd Command window has its own code format, so will look at the garbled, If you run it with Eclipse, it won't.
It's also important to note that if you subscribe to a channel using REDIS-CLI, which is Redis's client, then you won't be able to do anything except subscribe,unsubscribe,psubscribe after you subscribe, Punsubscribe any other orders that were unexpected in these four commands. I put a line of R.set (' s ', 32) in the subscription code, and it was executed during the execution, that is, when we use the programming language to manipulate Redis, we can still use other commands when we subscribe, so The restrictions on orders just mentioned are only for Redis own clients.