SpringBoot2.x集成MQTT實現消息推送(附源碼)

MQTT協議因低延遲、效率高在工業物聯網領域使用的頻率特別高,前面兩篇文檔分別對MQTT內容和MQTT服務器做了簡單介紹,今天本文從實戰的角度闡述如何用代碼實現發送MQTT消息。


1.引入相關的依賴


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>


2.在application.yml配置MQTT服務器信息


server:
  port: 9090
mqtt:
  host: tcp://127.0.0.1:1883
  clientinid: mqttinId
  clientoutid: mqttoutid
  topic: virus
  qoslevel: 1
  #MQTT 認證
  username:  xxx
  password: yyy
  # 10s
  timeout: 10000
  #20s
  keepalive: 20


3.配置MQTT消息推送配置


@Configuration
@IntegrationComponentScan
public class MqttSenderConfig {
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.host}")
    private String hostUrl;
    @Value("${mqtt.clientinid}")
    private String clientId;
    @Value("${mqtt.topic}")
    private String defaultTopic;
    @Value("${mqtt.timeout}")
    private int completionTimeout;
    @Bean
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setConnectionTimeout(10);
        mqttConnectOptions.setKeepAliveInterval(90);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(2);
        return mqttConnectOptions;
    }
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =  new MqttPahoMessageHandler(clientId, mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }
}


4.MQTT消息推送接口


@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateway {
    void sendToMqtt(String data, @Header(MqttHeaders.TOPIC) String topic);
}


5.MQTT消息推送API


@RestController
public class MessageController {
    @Autowired
    MqttGateway mqttGateway;
    @RequestMapping("/sendMqttMessage")
    public String sendMqttMessage(String message, String topic) {
        mqttGateway.sendToMqtt(message, topic);
        return "ok";
    }
}


測試


接下來就可以在POSTMAN中進行測試了,輸入消息內容和主題,就可以在相應的頻道發送消息了。如果使用其它的消息客戶端進行測試的話,可以接受到消息。


http://localhost:9090/sendMqttMess age?message=戰勝武漢肺炎&topic=virus


message: xxx

topic: xxx



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章