您的位置:首页 > 其它

EMQX的web_hook使用心得

Z_xiansheng11 2020-07-21 04:15 561 查看 https://blog.csdn.net/z_xiansh

EMQX的web_hook使用心得-java


emqx自带的web_hook插件可以解决很多需求,比如监听设备的上下线,设备的订阅与发布等等:

  1. 修改配置文件;
    emq的配置文件在 emqx安装目录/etc/plugins
    vim emqx_web_hook.conf
    修改web.hook.api.url ,将其改为自定义的接口

    注释掉不用的事件。具体事件类别可查看官网
    注意:修改完配置后重启生效
  2. 接口;
/**
* @author zhangyr
*/
@RestController
@RequestMapping
@Api(tags = "emq的webHook管理")
@AllArgsConstructor
@Slf4j
public class WebHookApi {
@PostMapping("/webHook")
public void receiveWebHookData(@RequestBody Map<String, Object> param) {
//测试内容
log.info("监听到客户端活动信息=========");
Iterator it = param.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
Object value = entry.getValue();
log.info(key + "=====" + value.toString());
}
log.info("以上是接收的所有信息=========");
//设备连接成功
if (WebHookConstant.ACTION_CONNECTED.equals(action)) {
log.info("设备连接成功=========");
}
//设备断开连接成功
if (WebHookConstant.ACTION_DISCONNECTED.equals(action)) {
log.info("设备断开连接成功=========");
}
//设备数据上传
if (WebHookConstant.MESSAGE_PUBLISH.equals(action)) {
log.info("设备数据上传=========");
}
}

可定义一个类来区分事件

public class WebHookConstant {
//固定的属性名
public static final String ACTION = "action";
public static final String CLINET_ID= "clientid";
public static final String USERNAME = "username";
public static final String REASON = "reason";
public static final String TOPIC = "topic";
public static final String PAYLOAD = "payload";

//消息的事件戳
public static final String TS = "ts";
//QoS 等级
public static final String QOS = "qos";
//消息来源用户名
public static final String FROM_USERNAME = "from_username";
//消息clientId
public static final String FROM_CLIENT_ID = "from_client_id";
//ACTION
/**断开连接*/
public static final String ACTION_DISCONNECTED = "client_disconnected";
/**成功连接*/
public static final String ACTION_CONNECTED = "client_connected";
/**上传数据*/
public static final String MESSAGE_PUBLISH = "message_publish";
}

测试结果

标签: