HTTP、CoAP发送PUBLISH消息

针对一些下位机或特殊应用场景中无法使用MQTT客户端情况可使用此功能通过HTTP或CoAP协议推送消息到Coolpy7内核进行消息发布。v7.3.2.6开始支持本功能。

架构

HTTP协议发布消息

  1. 通过POST方法调用接口

  2. 通过Header中添加Basic Auth信息进行用户名、密码提交(与MQTT连接的UserName,PassWord保持一致

  3. 通过URL中的Query参数设置MQTT消息参数

  4. Coolpy7节点收到请求后保持与原用户身份验证功能调用扩展服务进行用户身份验证,验证成功后消息将发布到MQTT网络中

Basic Auth算法, 以半角":"号组合用户名和密码,然后进行Base64进行编码放到http的header中,header 键为Authorization,值以Basic加一个空格为前缀, 然后并上用户名密码的base64值

例如:Basic amFjb2I6cGFzcw==

CURL使用示例

curl -v -X POST -H "Authorization: Basic c3R1ZGVudDpzdHVkZW50" "Content-Type: application/json" -d '{"id":100}' 'http://localhost:8888/pub?clientid=jacoblai&topic=testtopic/+/a/&qos=0&retain=false'

性能测试 (WRK压测)

wrk -t 16 -c 1000 -d 10s --latency --timeout 5s -s ./post.lua 'http://localhost:8081/pub?clientid=jacoblai&topic=testtopic/a&qos=0&retain=false'
Running 10s test @ http://localhost:8081/pub?clientid=jacoblai&topic=testtopic/a&qos=0&retain=false
16 threads and 1000 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 8.14ms 3.05ms 45.08ms 65.95%
Req/Sec 4.47k 2.16k 66.48k 89.63%
Latency Distribution
50% 8.93ms
75% 10.11ms
90% 11.79ms
99% 12.90ms
712972 requests in 10.10s, 233.35MB read
Socket errors: connect 0, read 918, write 0, timeout 0
Non-2xx or 3xx responses: 712972
Requests/sec: 70569.91
Transfer/sec: 23.10MB

post.lua压测提交测试内容

wrk.method = "POST"
wrk.body = '{"jsonrpc":"2.0","method":"cita_sendTransaction","params":["abcd"],"id":2}'
wrk.headers["Content-Type"] = "application/json"

CoAP协议发布消息

  1. 通过SetOption的LocationQuery参数设为Basic Auth身份验证信息

  2. 通过SetOption的URIQuery参数设置publish参数

消息示例

req := coap.Message{
Type: coap.Confirmable,
Code: coap.POST,
MessageID: uint16(rand.Intn(max-min) + min),
Payload: []byte(`{"data":"hello mqtt from coap"}`),
}
req.SetPathString("/pub")
req.SetOption(coap.LocationQuery, "Basic amFjb2I6cGFzcw==")
req.SetOption(coap.URIQuery, "clientid=jacoblai&topic=testtopic/+/a/#&qos=0&retain=false")

压力测试源代码:https://github.com/Coolpy7/coolpy7_benchmark/blob/master/test_coap_publish/coap_bench_pub_test.go

性能指标

goos: darwin
goarch: amd64
BenchmarkPub
BenchmarkPub-8 41418 28107 ns/op 633 B/op 10 allocs/op
PASS