OpenResty读取rabbitmq消息
时间: 2023-08-29 16:13:26 浏览: 218
用PHP收发RabbitMQ消息
4星 · 用户满意度95%
OpenResty可以通过lua-resty-rabbitmq这个Lua库连接RabbitMQ并读取消息。该库提供了一种异步、非阻塞的方式来消费消息。您可以在OpenResty的Nginx配置文件中使用此库,例如:
```lua
local cjson = require "cjson"
local resty_rabbitmq = require "resty.rabbitmqstomp"
local mq_host = "localhost"
local mq_port = 61613
local mq_login = "guest"
local mq_password = "guest"
local mq_vhost = "/"
local mq_queue_name = "my_queue"
-- 创建连接
local mq,err = resty_rabbitmq:new()
if not mq then
ngx.log(ngx.ERR,"failed to create mq object: ",err)
return
end
-- 连接RabbitMQ
local ok,err = mq:connect({
host = mq_host,
port = mq_port,
login = mq_login,
password = mq_password,
vhost = mq_vhost,
})
if not ok then
ngx.log(ngx.ERR,"failed to connect to RabbitMQ: ", err)
return
end
-- 订阅队列
ok,err = mq:subscribe({
destination = mq_queue_name,
ack = "client",
})
if not ok then
ngx.log(ngx.ERR,"failed to subscribe queue: ", err)
return
end
while true do
-- 从队列中接收消息
local res,err = mq:receive()
if res then
ngx.log(ngx.INFO,"received msg: ", cjson.encode(res.body))
else
ngx.log(ngx.ERR,"failed to receive message: ", err)
end
end
```
这段代码将连接到名为"my_queue"的队列并不断地从中接收消息。每当获取到消息时,将会打印到Nginx的错误日志中。
阅读全文