SpringBoot简单集成MQTT

SpringBoot简单集成MQTT

	记录:这两天在写MQ的东西,就顺便记录下
	注意的是mqtt不能储存数据,就算储存也是只能储存最后一条,所以当服务端断了不能及时接收数据时容易造成数据丢失,但mqtt的优点就是省流量
1.导入依赖

<dependency>
    <groupId>org.eclipse.pahogroupId>
    <artifactId>org.eclipse.paho.client.mqttv3artifactId>
    <version>1.2.0version>
dependency>
<dependency>
    <groupId>org.fusesource.mqtt-clientgroupId>
    <artifactId>mqtt-clientartifactId>
    <version>1.14version>
dependency>
2.添加配置文件 application.yml
#MQTT配置信息
#MQTT-用户名
spring.mqtt.username: (账号)
#MQTT-密码
spring.mqtt.password: (密码)
#MQTT-服务器连接地址,如果有多个,用逗号隔开,如:tcp://127.0.0.1:61613,tcp://192.168.2.133:61613
spring.mqtt.url: tcp://IP:1883(端口默认1883)
#MQTT-连接服务器默认客户端ID
spring.mqtt.client.id: 1
#MQTT-消息订阅主题,实际可在调用接口时指定,如果有多个,用逗号隔开,
spring.mqtt.topic: /ksp/test
#连接超时
spring.mqtt.completionTimeout: 3000
3.编写配置类
@Component
public class MqttCofigBean {

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

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

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

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

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

    @Value("${spring.mqtt.completionTimeout}")
    private int completionTimeout;//连接超时

    /**
     * 获取用户名
     * @return
     */
    public String getUsername() {
        return this.username;
    }
    /**
     * 获取密码
     * @return
     */
    public String getPassword() {
        return this.password;
    }
    /**
     * 获取服务器连接地址
     * @return
     */
    public String getHostUrl() {
        return this.hostUrl;
    }
    /**
     * 获取客户端ID
     * @return
     */
    public String getClientId() {
        return this.clientId;
    }
    /**
     * 获取默认主题
     * @return
     */
    public String[] getMsgTopic() {
        String[] topic=msgTopic.split(",");
        return topic;
    }
    /***
     * 获取连接超时时间
     * @return
     */
    public int getCompletionTimeout() {
        return this.completionTimeout;
    }

}
4.编写客户端
@Component
public class MqttConsumer implements ApplicationRunner {

    private static Logger logger= LoggerFactory.getLogger(MqttConsumer.class);

    private static MqttClient client;

    private static MqttTopic mqttTopic;

    /**
     * MQTT连接属性配置对象
     */
    @Autowired
    public MqttCofigBean mqttCofigBean;

    /**
     * 初始化参数配置
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("初始化启动MQTT连接");
        this.connect();
    }


    /**
     *  用来连接服务器
     */
    private void connect() throws Exception{
        client = new MqttClient(mqttCofigBean.getHostUrl(),mqttCofigBean.getClientId(), new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(mqttCofigBean.getUsername());
        options.setPassword(mqttCofigBean.getPassword().toCharArray());
        //是否清除session
        options.setCleanSession(false);
        // 设置超时时间
        options.setConnectionTimeout(30);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            String[] msgtopic = mqttCofigBean.getMsgTopic();
            //订阅消息
            int[] qos = new int[msgtopic.length];
            for (int i = 0; i < msgtopic.length; i++) {
                qos[i]=0;
            }
            client.setCallback(new TopMsgCallback(client,options,msgtopic,qos));
            client.connect(options);
            client.subscribe(msgtopic,qos);
            logger.info("MQTT连接成功:"+mqttCofigBean.getClientId()+":"+client);
        } catch (Exception e) {
            logger.error("MQTT连接异常:"+e);
        }
    }


    /**
     * 重连
     * @throws Exception
     */
    public void reConnect() throws Exception {
        if(null != client) {
            this.connect();
        }
    }

    /**
     * 订阅某个主题
     * @param topic
     * @param qos
     */
    public void subscribe(String topic,int qos){
        try {
            logger.info("topic:"+topic);
            client.subscribe(topic, qos);
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setPayload(new String("消息11111111").getBytes());
            client.publish(topic,mqttMessage);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public MqttClient getClient() {
        return client;
    }

    public void setClient(MqttClient client) {
        this.client = client;
    }

    public MqttTopic getMqttTopic() {
        return mqttTopic;
    }

    public void setMqttTopic(MqttTopic mqttTopic) {
        this.mqttTopic = mqttTopic;
    }

}
5.编写服务端
@Component
public class TopMsgCallback implements MqttCallback {

    private static Logger logger= LoggerFactory.getLogger(TopMsgCallback.class);

    private MqttClient client;
    private MqttConnectOptions options;
    private String[] topic;
    private int[] qos;

    public TopMsgCallback() {}

    public TopMsgCallback(MqttClient client, MqttConnectOptions options,String[] topic,int[] qos) {
        this.client = client;
        this.options = options;
        this.topic=topic;
        this.qos=qos;
    }
    /**
     * 断开重连
     */
    public void connectionLost(Throwable cause) {
        logger.info("MQTT连接断开,发起重连");
        while(true) {
            try {
                Thread.sleep(30000);
                client.connect(options);
                //订阅消息
                client.subscribe(topic,qos);
                logger.info("MQTT重新连接成功:"+client);
                break;
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }

    }
    /**
     * 接收到消息调用令牌中调用
     */
    public void deliveryComplete(IMqttDeliveryToken token) {
    }

    /**
     * 消息处理
     */
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        //订阅消息字符
        String msg = new String(message.getPayload());
        logger.info("topic:"+topic);
        logger.info("msg:"+msg);
    }

    //对象转化为字节码
    public  byte[] getBytesFromObject(Serializable obj) throws Exception {
        if (obj == null) {
            return null;
        }
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        return bo.toByteArray();
    }

}

你可能感兴趣的:(SpringBoot简单集成MQTT)