Spring Boot整合MQTT 使用账号密码

 

依赖,根据需要放入

  <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.5</version>
        </dependency>

 

配置信息

spring:
  mqtt:
    clientId: Cldemoqw
    url: tcp://boqx.o:1883
    username: no
    password: no

 

 

配置类  ,账号密码需要就打开注释

MqttConfig.java   

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@Slf4j
public class MqttConfig {

    @Value("${spring.mqtt.url}")
    private String serverURI;

    @Value("${spring.mqtt.clientId}")
    private String clientId;

    @Value("${spring.mqtt.clientId}")
    private String username;

    @Value("${spring.mqtt.clientId}")
    private String password;



    private  static MqttClient mqttClient;
    private  static MqttClient sendMqttClient;
    static String serverURI2;



    @Resource
    private  MqttMessageListenerImpl mqttMessageListenerImpl;




    public static MqttClient getSendClient() {

        return sendMqttClient;
    }


    static MqttConnectOptions opts;
    @Bean
    MqttConnectOptions mqttConnectOptions() {
        try {
            opts = new MqttConnectOptions();
            opts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
            opts.setMaxReconnectDelay(5 * 1000);
            opts.setConnectionTimeout(2 * 1000);
            opts.setHttpsHostnameVerificationEnabled(false);
            opts.setCleanSession(false);
            opts.setKeepAliveInterval(5);
            opts.setAutomaticReconnect(true);
         //  opts.setUserName(username);
         //  opts.setPassword(password.toCharArray());

        } catch (Exception e) {
            e.printStackTrace();
        }
        serverURI2=serverURI;
        return opts;
    }


    @Bean
    MqttClient sendMqttClient() {
        MqttClient sendClient = null;
        try {

            MemoryPersistence persistence = new MemoryPersistence();
            sendClient = new MqttClient(serverURI, clientId+"send", persistence);
            IMqttToken token = sendClient.connectWithResult(opts);
            token.waitForCompletion();
            sendMqttClient = sendClient;
        } catch (MqttException e) {
            log.error(e.getMessage());

        }
        return sendMqttClient;
    }
    @Bean
    MqttClient mqttClient()  {
        MqttClient client = null;
        try {

            MemoryPersistence persistence = new MemoryPersistence();
            client = new MqttClient(serverURI, clientId, persistence);
            IMqttToken token = client.connectWithResult(opts);
            token.waitForCompletion();

            log.info("=====================订阅所有mqtt服务端下发信息====================");

            IMqttToken iMqttToken = client.subscribeWithResponse("topic/test1", 2, mqttMessageListenerImpl);
            iMqttToken.waitForCompletion();
            String str = new String(token.getResponse().getPayload());
            System.out.println("============================" + str);
            mqttClient = client;
        } catch (MqttException e) {
            log.error(e.getMessage());

        }
        return client;
    }



}

 

回调类

MqttMessageListenerImpl.java

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;


/**
 * @ClassName: MqttMessageListenerImpl
 */
@Component
@Slf4j
public class MqttMessageListenerImpl implements IMqttMessageListener {



    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("开始");

        System.out.println("订阅主题名称:"+topic);

        String payload = new String(message.getPayload());

        System.out.println("发送数据:"+payload);

        return;
    }


}

 

 

发送demo

String str="nihao";
        try {
            MqttConfig.getSendClient().publish("testtopic/12", str.getBytes(), 1, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }

 

posted @ 2023-01-17 17:41  yvioo  阅读(1384)  评论(0编辑  收藏  举报