快速入门
-
依赖
<dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency> -
配置mqtt
@Configuration public class MqttConfig { @Bean public MqttClient init() throws MqttException { String broker = "tcp://broker.emqx.io:1883"; String clientId = MqttClient.generateClientId(); MemoryPersistence persistence = new MemoryPersistence(); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setUserName("emqx_user"); connOpts.setPassword("emqx_password".toCharArray()); connOpts.setKeepAliveInterval(10); connOpts.setAutomaticReconnect(true); // 建立连接 MqttClient client = new MqttClient(broker, clientId, persistence); client.setCallback(new SampleCallback()); client.connect(connOpts); System.out.println("成功连接到服务器:" + broker); // 订阅 String topic = "test/topic"; client.subscribe(topic,2); System.out.println("订阅了主题:" + topic); return client; } } -
创建回调类
SampleCallbackpublic class SampleCallback implements MqttCallback { // 连接丢失 public void connectionLost(Throwable cause) { System.out.println("连接丢失:connection lost:" + cause.getMessage() + ",连接丢失时间:" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); } // 收到消息 public void messageArrived(String topic, MqttMessage message) { System.out.println("收到消息:\n topic:" + topic + "\n Qos:" + message.getQos() + "\n payload:" + new String(message.getPayload())); } // 消息传递成功 public void deliveryComplete(IMqttDeliveryToken token) { System.out.println("消息投递成功"); } } -
测试
@RestController public class MyController { @Autowired private MqttClient client; @RequestMapping("testMqtt") public String test() throws MqttException { String topic = "test/topic"; String content = "你好呀,我们都在用免费的mqtt服务器"; MqttMessage message = new MqttMessage(content.getBytes()); message.setQos(2); client.publish(topic, message); return "success"; } }