python redis订阅_Python -- Redis 发布订阅

一、前言

Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

Redis 客户端可以订阅任意数量的频道。

下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:

当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:

二、事例

Demo:

import redis

class RedisHelper:

def __init__(self):

self.__conn = redis.Redis(host='172.16.200.49')

self.chan_sub = 'fm104.5'

self.chan_pub = 'fm104.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

订阅者:

# -*- coding: UTF-8 -*-

from redis_helper import RedisHelper

obj = RedisHelper()

redis_sub = obj.subscribe()

while True:

msg = redis_sub.parse_response()

print(msg)

发布者:

# -*- coding: UTF-8 -*-

from redis_helper import RedisHelper

obj = RedisHelper()

while True:

msg = input('>>:')

obj.public(msg)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值