r3c支持发布订阅吗,怎么使用,有demo吗
时间: 2023-07-15 22:15:20 浏览: 55
是的,r3c支持发布/订阅模式。在r3c中,发布者可以将消息发布到指定的频道,而订阅者可以订阅一个或多个频道以接收相应的消息。以下是使用r3c进行发布/订阅的基本步骤:
1. 创建redis连接
首先需要创建redis连接,可以使用r3c提供的`RedisClient`类。例如:
```python
from r3c import RedisClient
client = RedisClient(host='localhost', port=6379)
```
2. 发布消息
要发布消息,可以使用`publish`方法。例如,要向名为`news`的频道发布一条消息,可以使用以下代码:
```python
client.publish('news', '这是一条新闻')
```
3. 订阅频道
要订阅一个或多个频道,可以使用`subscribe`方法。例如,要订阅名为`news`和`weather`的频道,可以使用以下代码:
```python
def handle_message(channel, message):
print(channel, message)
client.subscribe(['news', 'weather'], handle_message)
```
在上面的代码中,`handle_message`函数是一个回调函数,当有新消息时,r3c将自动调用该函数。`handle_message`函数的第一个参数是频道名,第二个参数是消息内容。
4. Demo
下面是一个简单的示例程序,演示如何使用r3c进行发布/订阅:
```python
from r3c import RedisClient
client = RedisClient(host='localhost', port=6379)
def handle_message(channel, message):
print(channel, message)
client.subscribe(['news', 'weather'], handle_message)
client.publish('news', '这是一条新闻')
client.publish('weather', '天气晴朗')
```
在运行上述代码后,会输出以下内容:
```
news 这是一条新闻
weather 天气晴朗
```
这表明我们成功地发布和订阅了消息。