lua 通过 stomp协议发送消息到 rabbitmq

lua 发送消息到 rabbitmq, 我们选择类库lua-resty-rabbitmqstomp 来完成这个任务。

类库安装:

进入 nginx.conf 中 lua_package_path 中对应的目录下的resty 目录(没有则创建) , 执行:

wget -c https://raw.githubusercontent.com/wingify/lua-resty-rabbitmqstomp/master/lib/resty/rabbitmqstomp.lua

示例代码:

local rabbitmq = require "resty.rabbitmqstomp"
local cjson = require "cjson"

local opts = {
    host = '127.0.0.1',
    port = '5672',
    username = 'guest',
    password = 'guest',
    vhost = '/'
}

local mq, err = rabbitmq:new(opts)

if not mq then
    ngx.say('cannot new mq')
    ngx.say(err)
    return
end

mq:set_timeout(10000)

local ok, err = mq:connect(HOST, PORT)
if not ok then
    ngx.say('cannot connect mq' .. err)
    return
end

local headers = {}
-- 消息发送到哪里 /exchange/交换机名称/routing_key名称
headers["destination"] = "/exchange/ex1/ex1_key"
-- 是否持久化
headers["persistent"] = "true"
-- 消息格式
headers["content-type"] = "application/json"

local ok, err = mq:send(cjson.encode(data), headers)
if not ok then
    ngx.say('cannot send mq')
    return
end

-- 消息保持长连接,第一个参数表示连接超时时间,第二个参数是表示连接池大小
-- 由于 rabbitmq 连接建立比较耗时,所以保持连接池是非常必要的
local ok, err = mq:set_keepalive(10000, 500)
if not ok then
    ngx.say(err)
    return
end

注意: rabbitmq 的 stomp 协议支持默认是不开启的,测试前需要手动开启:

rabbitmq-plugins enable rabbitmq_stomp

另外与 lua 发送消息到 Rabbitmq 中使用 的类库比,本文使用的方式性能更高,单机性能测试达到了5000 qps

转自:http://www.dahouduan.com/2017/12/07/lua-stomp-rabbitmq/?_blank

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...