https://segmentfault.com/a/1190000016898228?utm_source=coffeephp.com
method one:
redis_helper.py: publish and subscribe packaging method
Redis Import class RedisHelper ( Object ): DEF __init __ (Self): Self .__ conn = redis.Redis (Host = " localhost " ) # subscribe self.chan_sub = " fm104.5 " DEF public (Self, msg): "" " posted a message on the specified channel : param msg: : return : " "" # publish (): the number of messages posted on a specified channel, subscribers return of Self .__ conn.publish (self.chan_sub, msg) return True DEF the Subscribe (self): # return publish-Subscribe object, this object you can 1) Subscribe to channel 2) Monitor the news channels Pub = Self .__ conn.pubsub () as specified () is # to subscribe, and publish channels. Message will be posted to this channel pub.subscribe (self.chan_sub) RET = pub.parse_response () # [B ' Subscribe ' , B ' fm86 ' , . 1 ] Print ( " RET:% S " % RET) return Pub
redis_pub.py: publisher
from redis_helper import RedisHelper obj = RedisHelper() for i in range(5): obj.public("hello_%s" % i)
redis_sub.py: Subscribers
from redis_helper import RedisHelper obj = RedisHelper() redis_sub = obj.subscribe() while True: msg = redis_sub.parse_response() print(msg)
Method Two:
redis_helper.py: publish and subscribe packaging method
Redis Import class RedisHelper ( Object ): DEF __init __ (Self): Self .__ conn = redis.Redis (Host = " localhost " ) # channel name self.chan_sub = " the Orders " DEF public (Self, msg): "" " in post messages on the specified channel : param msg: : return : "" " # publish (): dissemination of information on a specified channel, returns the number of subscribers Self .__ conn.publish (self.chan_sub, msg) return True DEF the Subscribe (Self ): # returns publication subscriptions object, this object you can 1) Subscribe to channel 2) Monitor the news channels Pub = Self .__ conn.pubsub () # subscribe to a channel, and publish as specified channel (). Message posted to this channel pub.subscribe (self.chan_sub) return Pub
redis_pub.py:
from redis_helper import RedisHelper obj = RedisHelper() for i in range(5): obj.public("hello_%s" % i)
redis_sub.py:
from redis_helper import RedisHelper obj = RedisHelper() redis_sub = obj.subscribe() while True: # listen()函数封装了parse_response()函数 msg = redis_sub.listen() for i in msg: if i["type"] == "message": print(str(i["channel"], encoding="utf-8") + ":" + str(i["data"], encoding="utf-8")) elif i["type"] == "subscrube": print(str(i["chennel"], encoding="utf-8"))
The difference is that the above two ways, a way of using the publish-subscribe parse_response object () method to get subscription information, the way two objects using a publish-subscribe listen () method to get subscription information. listen () method is the encapsulation of parse_response () method, the addition of blocking, the results and parse_response () returns have been processed, so that the results easier.