第一步、安装rabbitmq

docker run -itd --name rabbitmq -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin1234 --network=host rabbitmq:3-management

openresty的下载这里就不赘述了

window安装如下

https://openresty.org/download/openresty-1.21.4.2-win32.zip

https://openresty.org/download/openresty-1.21.4.2-win64.zip

linux的安装去参考一下这个文档

http://openresty.org/en/linux-packages.html#centos

第二步、开启 stomp插件功能

docker exec -it rabbitmq rabbitmq-plugins enable rabbitmq_stomp
查看运行状态
docker exec -it rabbitmq rabbitmqctl status
出现如下一行就是开启成功了
Interface: [::], port: 61613, protocol: stomp, purpose: STOMP

第三步、配置nginx.conf

在http节点里面在server节点外面配置源文件目录
lua_package_path "D:/project/project_name/src/?.lua;;";
在server的location里面添加需要执行的文件
content_by_lua_file D:/project/project_name/src/test.lua;

配置实例如下

http {
    server {
        listen       [::]:80;
        server_name  [::]:localhost;
        set $HOST_TYPE prodT;
        location / {
          content_by_lua_file D:/project/project_name/src/test.lua;
          add_header Content-Type 'text/html;charset=utf-8';
        }
    }
}


第四步、编写lua文件

安装 rabbitmqstomp.lua 文件放到 openresty-1.21.4.1-win64\lualib\resty 路径下

文件地址:https://www.csdcb.cn/article/rabbitmqstomp.html

当然也可以去github去找源库文件


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

local opts = {
    host = '192.168.1.11',
    port = 61613,
    username = "admin",
    password = "admin1234",
    vhost = "/" }

-- 第一步、创建mq对象
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(opts.host,opts.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(headers), 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

 

最后修改于 2023-10-18 20:06:10
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇