#conding=utf-8
#一、创建redis类 文件名 RedisHelper
import redis
# conn=redis.Redis(host='127.0.0.1')
# import redis
class RedisHelper:
def __init__(self):
# self.__conn = redis.Redis(host='47.94.18.xxx')
self.__conn = redis.Redis(host='127.0.0.1')
self.chan_sub = '104.5' # 接收频道
self.chan_pub = '104.5' # 发送频道
#发布者
def public(self, msg):
self.__conn.publish(self.chan_pub, msg)
return True
#订阅者
def subscribe(self):
pub = self.__conn.pubsub()#将频道调到所需的频道
pub.subscribe(self.chan_sub) #开始监听
pub.parse_response() #测试是否开始监听
return pub
#二、Public
#conding=utf-8
from RedisHelper import RedisHelper
obj = RedisHelper()
obj.public('Hello I am public')
#三、subscribe
#conding=utf-8
from RedisHelper import RedisHelper
obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
msg = redis_sub.parse_response()
print(msg)