自学内容网 自学内容网

redis 消息订阅命令

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

1. SUBSCRIBE 命令

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

SUBSCRIBE channel1 channel2

2. UNSUBSCRIBE 命令

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

UNSUBSCRIBE channel1 channel2

3. PUBLISH 命令

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

PUBLISH channel1 "Hello, World!"

4. PSUBSCRIBE 命令

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

PSUBSCRIBE news.*

示例

1. 订阅和接收消息

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

redis-cli
> SUBSCRIBE channel1

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

2. 发布消息

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

redis-cli
> PUBLISH channel1 "Hello, Channel 1!"

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

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

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

redis-cli
> PSUBSCRIBE news.*

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

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

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 频道
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 消息
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 中实现基本的消息订阅和发布功能。


原文地址:https://blog.csdn.net/xuanyuanjiaqi/article/details/140157566

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!