使用用户自定义事件
如下文代码,创建了用户自定义事件 user_myevent
, 事件内容为通过数据处理后的总累计流量
、总累计电量
local log = require("log")
local json = require("json")
local http = require("http")
-------------------------------------------------------------------------------------
--[[
示例,用户自定义事件
]]
-------------------------------------------------------------------------------------
local prog_name = "用户自定义事件" --程序名称,日志
Host = "http://hyperf:9501" --请求主域
mmq_url = ""
user_event_name = "user_myevent"
function Run()
get_mmq_url()
while true do
times = os.time()
if times % 60 == 0 then -- 定时60s执行一次
local event_body = {
["GAS_total"] = 0, --总累计流量
["ELE_total"] = 0, --总累计电量
["time"] = 0, --时间
}
-- ... 这里写你的数据来源,处理逻辑;省略n行代码
event_body["GAS_total"] = 12345.67
event_body["ELE_total"] = 2345.67
event_body["time"] = times
local res_event = pub_user_event(event_body) --发事件
end
end
end
function get_mmq_url()
res, err = http.get("http://consul:8500/v1/agent/health/service/name/mmq")
if (err ~= nil) then
show("ERROR(get_mmq_url)", err)
return
end
response = json.decode(res["body"])
mmq_url = "http://" .. response[1]["Service"]["Meta"]["api_mode_http"]
end
function pub_user_event(event_body)
local response, error = http.post(mmq_url .. "/api", {
headers = {
["Content-Type"] = "application/json"
},
body = json.encode({
action = "pub_user_event",
user_event = {
user_event = user_event_name,
data = event_body,
datetime = os.date("%Y-%m-%d %H:%M:%S")
}
}),
})
if (error ~= nil) then
show("ERROR(pub_user_event)", error)
return
end
response = json.decode(response["body"])
return response
end
function show(msg, info)
local str_info = ""
if type(info) == "table" then
str_info = json.encode(info)
elseif type(info) == "nil" then
str_info = ""
else
str_info = tostring(info)
end
msg = "prog_name:".. prog_name .. ";[" .. os.date("%Y-%m-%d %H:%M:%S") .. "];" .. msg
log.info(msg ..";" .. str_info)
--log.info(json_info)
end
Run()
在发送完事件数据后,我们可以映射表AGT 自定义事件数据,即可将事件数据转为对象数据。
[
[
"GAS_total",
"",
"总累计流量",
"AGT",
{
"event": "user_event",
"user_event": "user_myevent"
},
"data.GAS_total",
"",
"",
{
"default_value": 0
}
],
[
"ELE_total",
"",
"总累计电量",
"AGT",
{
"event": "user_event",
"user_event": "user_myevent"
},
"data.ELE_total",
"",
"",
{
"default_value": 0
}
]
]
- AGT
- “event”: “user_event” 用户自定义事件,固定配置
- “user_event”: “user_myevent” 即用户自定义事件名称
文档更新时间: 2024-05-28 12:15 作者:技术支持