目錄標題
- 一、開啟WebHook插件
- 二、系結web服務器
- 三、配置事件規則
- 四、創建web服務器
- (一)匯入pom依賴
- (二)改yml
- (三)代碼
- (四)測驗
一、開啟WebHook插件
這個功能是由emqx_web_hook插件提供支持的,WebHook有什么用,它用于監控一些規則,比如發布、訂閱訊息,當監控到這些規則觸發時,會向web服務器(spring boot專案)發送一些資料(訊息),
這個功能是默認關閉的,我們先去開啟這個功能,

二、系結web服務器
[root@iz2zedg4ylq9iqtwm11wecz plugins]# pwd
/my/emqx/conf/etc/plugins
[root@iz2zedg4ylq9iqtwm11wecz plugins]# ls
acl.conf.paho emqx_lua_hook.conf
emqx_auth_http.conf emqx_lwm2m.conf
emqx_auth_jwt.conf emqx_management.conf
emqx_auth_ldap.conf emqx_prometheus.conf
emqx_auth_mnesia.conf emqx_psk_file.conf
emqx_auth_mongo.conf emqx_recon.conf
emqx_auth_mysql.conf emqx_retainer.conf
emqx_auth_pgsql.conf emqx_rule_engine.conf
emqx_auth_redis.conf emqx_sasl.conf
emqx_bridge_mqtt.conf emqx_sn.conf
emqx_coap.conf emqx_stomp.conf
emqx_dashboard.conf emqx_telemetry.conf
emqx_exhook.conf emqx_web_hook.conf
emqx_exproto.conf
[root@iz2zedg4ylq9iqtwm11wecz plugins]# vim emqx_web_hook.conf
# 將web.hook.url 修改為自己web服務器(spring boot專案的請求地址)的地址,
# web.hook.url = http://127.0.0.1:8088/mqtt/webhook

注意:重啟emqx
[root@iz2zedg4ylq9iqtwm11wecz plugins]# docker restart myemqx
myemqx
三、配置事件規則
# 檔案所在位置:
/etc/plugins/emqx_web_hook.conf

事件規則的詳情可以查看**官網**
## 格式示例
web.hook.rule.<Event>.<Number> = <Rule>
## 示例值
web.hook.rule.message.publish.1 = {"action": "on_message_publish", "topic": "a/b/c"}
web.hook.rule.message.publish.2 = {"action": "on_message_publish", "topic": "foo/#"}
四、創建web服務器
直接創建spring boot專案即可
(一)匯入pom依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
(二)改yml
# 注意這個埠號必須跟組態檔里面的一致
# /etc/plugins/emqx_web_hook.conf
# web.hook.url = http://127.0.0.1:8088/mqtt/webhoo
server.port=8088
(三)代碼

package com.lihua.webhook.controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author hs
* @date 2021/10/26 17:32
*/
@RestController
@RequestMapping("/mqtt")
public class WebHookController {
private Map<String,Boolean> clientStatus = new HashMap<>();
@PostMapping("/webhook")
public void hook(@RequestBody Map<String,Object> params){
System.out.println("emqx 觸發 webhook,請求體資料={}"+params);
String action = (String) params.get("action");
String clientId = (String) params.get("clientid");
if(action.equals("client_connected")){
System.out.println("客戶端{}接入本系統"+clientId);
clientStatus.put(clientId,true);
}
if(action.equals("client_disconnected")){
System.out.println("客戶端{}下線"+clientId);
clientStatus.put(clientId,false);
}
}
@GetMapping("/allStatus")
public Map getStatus(){
return this.clientStatus;
}
}
(四)測驗
啟動web hook服務器
連接一個客戶端,
斷開一個客戶端,
查看控制臺輸出

注意:1、如果測驗沒有反應可能時服務器地址寫錯了,如果使用docker安裝的話,ip一定不是127.0.0.1, 2、注意關閉win的防火墻

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/339268.html
標籤:其他
上一篇:Modbus RTU簡介(上)
