Python通过redis库来实现发布和订阅
import redis
class RedisHelper:
def __init__(self):
self.__conn = redis.Redis(host='192.168.5.124',password='XXXXX')
self.chan_pub = 'TaskManager.Redis.Channel'
self.chan_sub = 'TaskManager.Redis.Channel'
def public(self,msg):
self.__conn.publish(self.chan_pub, msg)
return True
def subscribe(self):
pub = self.__conn.pubsub()
pub.subscribe(self.chan_pub)
pub.parse_response()
return pub
rhl = RedisHelper()
msg = {
"name":'Tim'
}
redis_sub = rhl.subscribe()
rhl.public(json.dumps(msg))
while True:
msg = redis_sub.parse_response()
print(msg)
chan_pub是redis通信频道,连接同一个频道的发布者和订阅者能通信
如果redis库设置的密码,一定要加上password,不然会报错
浙公网安备 33010602011771号