python3 redis subscription and publishing demo example

created at 07-15-2021 views: 3

python3 redis subscription and publishing 

demo example

import redis

class RedisHelper:

    def __init__(self,host,port,db=0):
        self.__conn = redis.Redis(host,port,db=0)

    def public(self, channel, message):
    #Begin publishing news
        self.__conn.publish(channel, message)
        return True

    def subscribe(self,channel):
    #Start subscribing
        pub = self.__conn.pubsub()
    #Subscribe Channel
        pub.subscribe(channel)
    #Ready to receive
        pub.parse_response()
        return  pub

release

obj = RedisHelper()

obj.public('data','1111111')

subscription

obj= RedisHelper()

redis_sub = obj.subscribe('data')

while 1:
    msg =redis_sub.parse_response()
    # received
    print(msg)

The second way to subscribe

obj= RedisHelper()

redis_sub = obj.subscribe('data')

while 1:
    for item in pub.listen():
        # received
        print(item['data'])
created at:07-15-2021
edited at: 07-15-2021: