spring-boot集成mqtt

为了服务端和客户端的异步通信,采用mqtt,服务端和客户端订阅同一个topic,以此来通信。

mqtt的username可以自定义,password是md5(username)。

1、引入依赖

        
         
            org.eclipse.paho
            org.eclipse.paho.client.mqttv3
            1.2.0
        
        
            org.fusesource.mqtt-client
            mqtt-client
            1.14
        

2、添加配置类

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

/**
 * mqtt配置
 * @Author zyh
 * @Date 2020/7/9 15:59
 */
@Configuration
@RefreshScope
@Data
public class MqttConfig {

    /**
     * 主题前缀
     */
    @Value("${mqtt.topic.prefix}")
    private String topicPrefix;

    /**
     * level 0:最多一次的传输
     * level 1:至少一次的传输,(鸡肋)
     * level 2: 只有一次的传输
     */
    @Value("${mqtt.qos}")
    private int qos= 2;

    /**
     * 服务器连接地址,如果有多个,用逗号隔开,如:tcp://127.0.0.1:61613,tcp://192.168.2.133:61613
     */
    @Value("${mqtt.broker}")
    private String broker;

    /**
     * 当前服务clientId
     */
    @Value("${mqtt.clientId.prefix}")
    private String clientIdPrefix;

3、编写工具类

import lombok.extern.slf4j.Slf4j;
import net.go2global.common.core.util.UUIDUtils;
import net.go2global.service.translate.config.MqttConfig;
import org.apache.commons.codec.digest.DigestUtils;
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.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author zyh
 * @Date 2020/7/9 16:13
 */
@Slf4j
@Component
public class MqttClientUtils {

    @Autowired
    private MqttConfig mqttConfig;

    private MqttClient mqttClient=null;

    private MemoryPersistence persistence = new MemoryPersistence();

    private MqttConnectOptions connOpts = new MqttConnectOptions();

    /**
     * 发送消息
     * @param clientId
     * @param content
     * @throws MqttException
     */
    public void sendMsgToUser(String clientId,String content) throws MqttException {

        String topic=mqttConfig.getTopicPrefix()+clientId;

        MqttClient mqttClient = getMqttClient();

        log.info("sending msg to : "+clientId+",topic:"+topic+",content:"+content);

        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(mqttConfig.getQos());
        mqttClient.publish(topic, message);

        log.info("send success msg to : "+clientId+",topic:"+topic+",content:"+content);

        //disConnected();
    }

    /**
     * 获取client
     * @return
     * @throws MqttException
     */
    public synchronized MqttClient getMqttClient() throws MqttException {
        if(mqttClient==null){
            String clientId= mqttConfig.getClientIdPrefix()+UUIDUtils.getUUID();
            String username=UUIDUtils.getUUID();
            String md5Password= DigestUtils.md5Hex(username);
            char[] password = md5Password.toCharArray();

            connOpts.setUserName(username);
            connOpts.setPassword(password);

            connOpts.setCleanSession(true);
            mqttClient=new MqttClient(mqttConfig.getBroker(), clientId, persistence);
            log.info("Connecting to broker: "+mqttConfig.getBroker());
            mqttClient.connect(connOpts);
            log.info("Connected to broker: "+mqttConfig.getBroker());
        }

        if(!mqttClient.isConnected()){
            log.info("Connecting to broker: "+mqttConfig.getBroker());
            mqttClient.connect(connOpts);
            log.info("Connected to broker: "+mqttConfig.getBroker());
        }

        return mqttClient;
    }

    /**
     * 关闭连接
     * @throws MqttException
     */
    public synchronized void disConnected() throws MqttException {
        if(!mqttClient.isConnected()){
            log.info("disconnecting to broker: "+mqttConfig.getBroker());
            mqttClient.disconnect();
            log.info("disconnected to broker: "+mqttConfig.getBroker());
        }
    }

}

4、可以使用http://tools.emqx.io/connections/25bd3ff0-c1c1-11ea-91e9-199b8be7f6f6在线测试。

你可能感兴趣的:(spring-boot集成mqtt)