一、基础介绍


MQ库实现了各类消息代理中间件(Message Broker)的连接协议, 目前支持:redismqttstomp协议.

MQ库基于上述协议实现了: 生产者 -> 消费者与订阅 -> 发布模型, 可以在不依赖其它服务的情况下独立完成任务.

框架提供了多种MQ的封装, 当我们需要使用的时候需要根据实际的协议进行选择:

二、API预览


1. MQ:new


函数原型: MQ:new(opt)

此方法将会创建一个的MQ对象实例.

opt是一个table类型的参数, 里面可以包含如下内容:

  • host - String类型, 消息队列的域名或者IP地址.

  • port - Interge类型, 消息队列监听的端口.

  • auth - String类型, 如果后端MQ是Redis, 配置了连接口令则需要配置(可选);

  • db - Integer类型, 如果后端MQ是Redis, db范围在(0-16)(可选);

  • username - String类型, 仅在stomp/mqtt协议下用作登录认证(没有可以不填写).

  • password - String类型, 仅在stomp/mqtt协议下用作登录认证(没有可以不填写).

  • vhost - String类型, 仅在使用某些特定消息队列server的时候填写(例如:rabbit).

  • keepalive - Integer类型, 仅在使用mqtt的时候用来出发客户端主动发出心跳包的时间.

2. MQ:on


函数原型: MQ:on(pattern, callback)

此方法用来订阅一个指定pattern. 当接收到来自broker的推送消息后, callback将会被调用.

callback会被注入一个table类型的参数, 此参数将在断开连接的时候为nil(可用来判断服务器是否断开).

msg根据采用的协议的不同msg的内容也将有所不同.

3. MQ:emit


函数原型: MQ:emit(pattern, msg)

此方法用来向指定pattern发送消息, msgString类型.

单个MQ可以一直复用emit, 内部会创建一个写入队列去完成消息的顺序发送.

4. MQ:clsoe


函数原型: MQ:close()

此方法可以关闭不再使用的MQ; 在任何情况下, MQ对象使用完毕后都需要调用此方法来释放资源.

5. MQ:start


函数原型: MQ:start()

此方法在作为独立运行服务端时候调用.

三、开始实践


这里仅使用redis作为broker转发消息.

1. 生产/消费


我们模拟100个生产者向redis/queue内投递消息, 同时定义了一个消费者订阅/queue持续进行消费;

local cf = require "cf"
local json = require "json"
local Log = require "logging"
local MQ = require "MQ.redis"

cf.fork(function ()
  local consumer = MQ:new {
    host = "localhost",
    port = 6379
  }

  local count = 0
  consumer:on("/queue", function (msg)
    if not msg then
      Log:ERROR("[/queue]连接失败", "已经消费了"..count.."个消息")
      return
    end
    count = count + 1
    Log:DEBUG("开始消费:", msg, "已经消费了"..count.."个消息")
  end)

  consumer:start() -- Websoket内部无需使用这个方法
end)

for i = 1, 100 do
  cf.fork(function()

    local producer = MQ:new {
      host = "localhost",
      port = 6379
    }

    producer:emit("/queue", json.encode({
      code = 200,
      data = {
        id = math.random(1, 1 << 32)
      },
    }))

    producer:close()
  end)
end
[candy@MacBookPro:~/cfadmin] $ ./cfadmin
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":3912595079}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了1个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":2938696189}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了2个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":3499397173}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了3个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":1711272453}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了4个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":3968420025}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了5个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":1887895479}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了6个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":3687986737}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了7个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":2823099353}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了8个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":2528190121}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了9个消息
[2019-06-25 16:05:36,240] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":4107999865}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了10个消息
...
[2019-06-25 16:05:36,247] [@script/main.lua:19] [DEBUG] : 开始消费:, {["pattern"]="/queue", ["payload"]="{"code":200,"data":{"id":3608578767}}", ["source"]="/queue", ["type"]="pmessage"}, 已经消费了100个消息
[candy@MacBookPro:~/cfadmin] $

为了方便阅读. 我们这里取出前10条与最后第100条并且将msg的数据结构打印出来方便阅读.

消费者的处理方式采用同步非阻塞处理的(当前业务未处理完成是不会继续处理下个消息的), 如果不想阻塞当前消息队列事件循环可以考虑自行fork一个协程来处理.

2. 范围订阅


用户通过认证后接入到Server后订阅自己专属的频道, 当有用户专属消息的时候任何服务都可以利用此方法进行业务消息推送.

代码实现如下:

local cf = require "cf"
local json = require "json"
local Log = require("logging"):new()
local MQ = require "MQ.redis"

for uid = 1, 10 do
  cf.fork(function ()
    local client = MQ:new {
      host = "localhost",
      port = 6379
    }

    client:on("/user/"..uid.."/*", function (msg)
      if not msg then
        Log:ERROR("[/user/9257]连接失败")
        return
      end
      Log:DEBUG("UID:["..uid.."]接收到推送消息", msg)
    end)

    client:start() -- Websoket内部无需使用这个方法
  end)
end

local server = MQ:new {
  host = "localhost",
  port = 6379
}

cf.at(1, function (...)
  server:emit("/user/"..math.random(1, 10).."/ad", json.encode({
    code = 200,
    data = {}
  }))
end)

server:start()
[candy@MacBookPro:~/cfadmin] $ ./cfadmin
[2019-06-25 16:20:23,506] [@script/main.lua:18] [DEBUG] : UID:[9]接收到推送消息, {["source"]="/user/9/ad", ["pattern"]="/user/9/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:24,504] [@script/main.lua:18] [DEBUG] : UID:[4]接收到推送消息, {["source"]="/user/4/ad", ["pattern"]="/user/4/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:25,506] [@script/main.lua:18] [DEBUG] : UID:[8]接收到推送消息, {["source"]="/user/8/ad", ["pattern"]="/user/8/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:26,506] [@script/main.lua:18] [DEBUG] : UID:[8]接收到推送消息, {["source"]="/user/8/ad", ["pattern"]="/user/8/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:27,505] [@script/main.lua:18] [DEBUG] : UID:[10]接收到推送消息, {["source"]="/user/10/ad", ["pattern"]="/user/10/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:28,506] [@script/main.lua:18] [DEBUG] : UID:[2]接收到推送消息, {["source"]="/user/2/ad", ["pattern"]="/user/2/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:29,506] [@script/main.lua:18] [DEBUG] : UID:[4]接收到推送消息, {["source"]="/user/4/ad", ["pattern"]="/user/4/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:30,506] [@script/main.lua:18] [DEBUG] : UID:[8]接收到推送消息, {["source"]="/user/8/ad", ["pattern"]="/user/8/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:31,505] [@script/main.lua:18] [DEBUG] : UID:[3]接收到推送消息, {["source"]="/user/3/ad", ["pattern"]="/user/3/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:32,506] [@script/main.lua:18] [DEBUG] : UID:[6]接收到推送消息, {["source"]="/user/6/ad", ["pattern"]="/user/6/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:33,506] [@script/main.lua:18] [DEBUG] : UID:[5]接收到推送消息, {["source"]="/user/5/ad", ["pattern"]="/user/5/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:34,503] [@script/main.lua:18] [DEBUG] : UID:[7]接收到推送消息, {["source"]="/user/7/ad", ["pattern"]="/user/7/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:35,506] [@script/main.lua:18] [DEBUG] : UID:[4]接收到推送消息, {["source"]="/user/4/ad", ["pattern"]="/user/4/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:36,506] [@script/main.lua:18] [DEBUG] : UID:[6]接收到推送消息, {["source"]="/user/6/ad", ["pattern"]="/user/6/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[2019-06-25 16:20:37,505] [@script/main.lua:18] [DEBUG] : UID:[10]接收到推送消息, {["source"]="/user/10/ad", ["pattern"]="/user/10/*", ["type"]="pmessage", ["payload"]="{"data":{},"code":200}"}
[candy@MacBookPro:~/cfadmin] $

这里我们可以看到, 我们可以通过一次通配符订阅就可以接收到所有下属pattern消息.

3. 消息广播


在各种领域内, 消息推送已经成为了一种最常见的业务. 我们现在来尝试利用MQ实现消息推送业务.

首先, 我们将script/main.lua的文件写入如下代码:

-- main.lua
local cf = require "cf"
local json = require "json"
local Log = require("logging"):new()
local MQ = require "MQ.redis"

for i = 1, 3 do
  cf.fork(function ()
    local uid = math.random(1, 1 << 32)
    local client_mq = MQ:new {
      host = "localhost", -- 主机名
      port = 6379,        -- 端口号
      -- db = nil,        -- 默认数据库
      -- auth = nil,      -- 密码
    }
    client_mq:on("/system/notice", function (msg)
      if not msg then
        Log:ERROR("['/system/notice'] SUBSCRIBE ERROR: 连接已断开.")
        return
      end
      Log:DEBUG("UID:["..uid.."]接收到消息: ", msg)
    end)

    client_mq:start()
  end)
end

local server_mq = MQ:new {
  host = "localhost", -- 主机名
  port = 6379,        -- 端口号
  -- db = nil,        -- 默认数据库
  -- auth = nil,      -- 密码
}

cf.at(3, function (args)
  server_mq:emit("/system/notice", json.encode({
    code = 200,
    msg = "系统即将关闭"
  }))
end)

server_mq:start()

这里我们用启动了3个协程来模拟用户订阅消息, 并且每个协程都使用不同的UID来打印. 然后再启动一个定时器模拟每三秒的消息推送业务.

打开终端运行./cfadmin后, 输出如下:

[candy@MacBookPro:~/cfadmin] $ ./cfadmin
[2019-06-25 15:43:24,842] [@script/main.lua:19] [DEBUG] : UID:[3363385555]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}
[2019-06-25 15:43:24,842] [@script/main.lua:19] [DEBUG] : UID:[1693861773]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}
[2019-06-25 15:43:24,842] [@script/main.lua:19] [DEBUG] : UID:[3608578767]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}

[2019-06-25 15:43:27,841] [@script/main.lua:19] [DEBUG] : UID:[3363385555]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}
[2019-06-25 15:43:27,841] [@script/main.lua:19] [DEBUG] : UID:[1693861773]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}
[2019-06-25 15:43:27,841] [@script/main.lua:19] [DEBUG] : UID:[3608578767]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}

[2019-06-25 15:43:30,841] [@script/main.lua:19] [DEBUG] : UID:[3363385555]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}
[2019-06-25 15:43:30,841] [@script/main.lua:19] [DEBUG] : UID:[1693861773]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}
[2019-06-25 15:43:30,841] [@script/main.lua:19] [DEBUG] : UID:[3608578767]接收到消息: , {["pattern"]="/system/notice", ["payload"]="{"msg":"系统即将关闭","code":200}", ["type"]="pmessage", ["source"]="/system/notice"}
[candy@MacBookPro:~/cfadmin] $

从终端的输出内容中可以看到, 我们确实每隔3秒就收到了一次消息推送.

四、高级特性


我们现在有个业务需求: 对基于Websocket协议的客户端实现业务推送.

因此需要建立一套基于httpd库的Websocket路由. 让我们打开script/main.lua文件并编写下面这样的代码:

local httpd require "httpd"

local app = httpd:new("Web")

app:ws('/ws', require "ws")

app:listen("0.0.0.0", 8080)

app:run()

建立与客户端的连接完成的同时, 我们还需要利用MQ库订阅/chat.

每当客户端发送消息过来触发on_message的时候, 都将会消息直接发布到/chat内部通过中转后实现推送聊天.

我们利用前面章节所学的Websocket指南, 编写一段简单的Websocket路由处理代码:

local MQ = require "MQ.redis"
local class = require "class"

local websocket = class("websocket")

function websocket:ctor (opt)
  self.ws = opt.ws
  self.id = math.random(1, 1 << 32)
end

function websocket:on_open ()
  self.mq = MQ:new { host = 'localhost', port = 6379 }
  self.mq:on("/chat", function (msg)
    if not msg then
      return
    end
    self.ws:send(msg.payload)
  end)
end

function websocket:on_message (data, typ)
  if self.mq then
    self.mq:emit("/chat", data)
  end
  print("客户端["..self.id.."]发送了消息:["..data.."]")
end

function websocket:on_error (error)

end

function websocket:on_close ()
  if self.mq then
    self.mq:close()
    self.mq = nil
  end
end

return websocket

注意: 我们需要记住当客户端连接断开的时候记得关闭订阅回收资源, 以免造成内存泄漏问题.

现在我们来尝试启动./cfadmin, 查看是否正常运行.

[candy@MacBookPro:~/cfadmin] $ ./cfadmin
[2019/06/25 20:11:59] [INFO] httpd正在监听: 0.0.0.0:8080
[2019/06/25 20:11:59] [INFO] httpd正在运行Web Server服务...

下载客户端工具, 并且安装到我们的Chrome浏览器上. 提取码: cgwr

然后运行客户端工具, 在地址栏输入localhost:8080/ws点击Connect, 然后开始向服务器发送消息.

然后你就在终端中, 看到类似这样的日志输出:

[2019/06/25 20:12:01] - ::1 - ::1 - /ws - GET - 101 - req_time: 0.000095/Sec
[2019/06/25 20:12:17] - ::1 - ::1 - /ws - GET - 101 - req_time: 0.000080/Sec
客户端[1693861773]发送了消息:[hello! 我是2]
客户端[1693861773]发送了消息:[hello! 我是2]
客户端[1693861773]发送了消息:[hello! 我是2]
客户端[1693861773]发送了消息:[hello! 我是2]
客户端[1693861773]发送了消息:[hello! 我是2]
客户端[1693861773]发送了消息:[hello! 我是2]
客户端[1693861773]发送了消息:[hello! 我是2]
[2019/06/25 20:12:23] - ::1 - ::1 - /ws - GET - 101 - req_time: 0.000052/Sec
客户端[3363385555]发送了消息:[hello! 我是1]
客户端[3363385555]发送了消息:[hello! 我是1]
客户端[3363385555]发送了消息:[hello! 我是1]
客户端[3363385555]发送了消息:[hello! 我是1]
客户端[3363385555]发送了消息:[hello! 我是1]
客户端[3363385555]发送了消息:[hello! 我是1]
客户端[3363385555]发送了消息:[hello! 我是1]
客户端[1693861773]发送了消息:[hello! 我是2]

五、结束


至此, cfadmin框架的基础教程也已经结束. 软件开发不仅需要师傅领进门, 个人修行也是一种能力的体现.

文章内容庞大与驳杂, 其实涉及的技术种类繁多; 如果有错误欢迎反馈, 这样我们更得到更加优质的文档阅读体验.

我们现在也有了讨论社区: 点击加入QQ群; 虽然人数不多, 但是都是一些兴趣相投的开发者.

如果您也对它比较感兴趣, 欢迎一起到群里来交流技术.

Copyright © CandyMi 2019-2022 all right reserved,powered by Gitbook该文件修订时间: 2021-03-26 23:16:14

results matching ""

    No results matching ""