<dependency> <groupId>net.dreamlu</groupId> <artifactId>jfinal-mica-mqtt-client</artifactId> <version>2.0.2</version> </dependency>
3、添加 slf4j-log4j12
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.33</version> </dependency>
MqttClientPlugin mqttClientPlugin = new MqttClientPlugin(); mqttClientPlugin.config(mqttClientCreator -> { // 设置 mqtt 连接配置信息 mqttClientCreator .clientId("clientId") // 按需配置,相同的会互踢 .ip("mqtt.dreamlu.net") .port(1883) .connectListener(Aop.get(MqttClientConnectListener.class)); }); me.add(mqttClientPlugin);
@Override public void onStart() { IMqttClientMessageListener clientMessageListener = Aop.get(TestMqttClientMessageListener.class); MqttClientKit.subQos0("#", clientMessageListener); }
MqttClientKit.publish("mica", "hello".getBytes(StandardCharsets.UTF_8));
public class MqttClientConnectListener implements IMqttClientConnectListener { @Override public void onConnected(ChannelContext channelContext, boolean isReconnect) { if (isReconnect) { System.out.println("重连 mqtt 服务器重连成功..."); } else { System.out.println("连接 mqtt 服务器成功..."); } } @Override public void onDisconnect(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) { System.out.println("mqtt 链接断开 remark:" + remark + " isRemove:" + isRemove); } }
public class TestMqttClientMessageListener implements IMqttClientMessageListener { @Override public void onMessage(String topic, MqttPublishMessage mqttPublishMessage, ByteBuffer byteBuffer) { System.out.println("收到消息 topic:" + topic + "内容:\n" + ByteBufferUtil.toString(byteBuffer)); } }
最后,mica-mqtt 开源地址:https://gitee.com/596392912/mica-mqtt 快来玩,欢迎反馈。