redis 消息订阅命令

在 Redis 中,消息订阅和发布是一种用于实现消息传递的机制。主要命令包括 SUBSCRIBEUNSUBSCRIBEPUBLISHPSUBSCRIBE 等。下面是如何使用这些命令的详细说明和示例。

1. SUBSCRIBE 命令

SUBSCRIBE 命令用于订阅一个或多个频道,以接收这些频道发布的消息。

bash 复制代码
SUBSCRIBE channel1 channel2

2. UNSUBSCRIBE 命令

UNSUBSCRIBE 命令用于取消订阅一个或多个频道。

bash 复制代码
UNSUBSCRIBE channel1 channel2

3. PUBLISH 命令

PUBLISH 命令用于向一个频道发布消息。

bash 复制代码
PUBLISH channel1 "Hello, World!"

4. PSUBSCRIBE 命令

PSUBSCRIBE 命令用于订阅与模式匹配的一个或多个频道。

bash 复制代码
PSUBSCRIBE news.*

示例

1. 订阅和接收消息

在一个 Redis 客户端中订阅频道:

bash 复制代码
redis-cli
> SUBSCRIBE channel1

此时,该客户端将进入订阅模式并等待来自 channel1 的消息。

2. 发布消息

在另一个 Redis 客户端中发布消息:

bash 复制代码
redis-cli
> PUBLISH channel1 "Hello, Channel 1!"

在第一个客户端中,你会看到如下输出:

复制代码
1) "message"
2) "channel1"
3) "Hello, Channel 1!"
3. 模式匹配订阅

在一个 Redis 客户端中订阅匹配模式的频道:

bash 复制代码
redis-cli
> PSUBSCRIBE news.*

此时,该客户端将接收所有匹配 news.* 模式的频道消息。

在另一个 Redis 客户端中发布消息:

bash 复制代码
redis-cli
> PUBLISH news.sports "Sports News"
> PUBLISH news.weather "Weather News"

在第一个客户端中,你会看到如下输出:

复制代码
1) "pmessage"
2) "news.*"
3) "news.sports"
4) "Sports News"
1) "pmessage"
2) "news.*"
3) "news.weather"
4) "Weather News"

使用 Lua 脚本进行消息订阅

在 OpenResty 或其他嵌入式 Lua 环境中,你可以使用 Lua 脚本与 Redis 进行交互。

1. 使用 Lua 脚本订阅 Redis 频道
lua 复制代码
local redis = require "resty.redis"
local red = redis:new()

red:set_timeout(1000) -- 1 sec

local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

local res, err = red:subscribe("channel1")
if not res then
    ngx.say("failed to subscribe: ", err)
    return
end

while true do
    local res, err = red:read_reply()
    if res then
        ngx.say("received message: ", res[3])
    else
        ngx.say("failed to read reply: ", err)
        break
    end
end
2. 使用 Lua 脚本发布 Redis 消息
lua 复制代码
local redis = require "resty.redis"
local red = redis:new()

red:set_timeout(1000) -- 1 sec

local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

local res, err = red:publish("channel1", "Hello, World!")
if not res then
    ngx.say("failed to publish: ", err)
    return
end

ngx.say("message published to channel1")

通过这些示例,你可以在 Redis 中实现基本的消息订阅和发布功能。

相关推荐
weelinking9 小时前
【产品】00_产品经理用Claude实现产品系列介绍
数据库·人工智能·sql·数据挖掘·github·产品经理
2301_803934619 小时前
Go语言如何做网络爬虫_Go语言爬虫开发教程【指南】
jvm·数据库·python
秋910 小时前
windows中安装redis
数据库·redis·缓存
Cosolar10 小时前
万字详解:RAG 向量索引算法与向量数据库架构及实战
数据库·人工智能·算法·数据库架构·milvus
想唱rap10 小时前
IO多路转接之poll
服务器·开发语言·数据库·c++
SeaTunnel11 小时前
AI 让 SeaTunnel 读源码和调试过时了吗?
大数据·数据库·人工智能·apache·seatunnel·数据同步
凯瑟琳.奥古斯特11 小时前
数据冗余与规范化的本质[数据库原理]
开发语言·数据库·职场和发展
_ku_ku_11 小时前
数据库系统原理 · SQL 数据定义、更新及数据库编程 · 自学总结
数据库·oracle
Mortalbreeze12 小时前
深度理解文件系统 ---- 从磁盘存储到内核存储
大数据·linux·数据库
2301_8039346112 小时前
MySQL 字段类型选择规范指南
jvm·数据库·python