SpringBoot整合Mqtt

1、pom文件

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

2、配置文件

mqtt.host=tcp://192.168.0.188:1883
mqtt.publisher=samplePublisher
# todo
mqtt.consumer=dampleConsumerprod2
mqtt.topic=/ddddd,/eeeee,/fffff,/ggggg
mqtt.username=
mqtt.password=
mqtt.timeout=5000
mqtt.qos=2,2,2,2
mqtt.cleanSession=false



3、代码  

MqttProperties
package com.example.demo.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * Minio 配置信息
 *
 * @author ruoiy
 */
@Configuration
@ConfigurationProperties(prefix = "mqtt")
@Data
public class MqttProperties {

    private String host;
    private Integer pakageSize;

    private String username;
    private String password;
    private String[] topic;
    private String publisher;
    private String consumer;
    private Integer timeout;
    private int[] qos;
    private String pre;
    private boolean cleanSession;


}

MqttConfig
package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.handler.LoggingHandler;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import java.util.Optional;

@Slf4j
@Configuration
public class MqttConfig {
    @Autowired
    private MqttProperties mqttProperties;

//    @Bean
//    public MqttPahoClientFactory mqttClientFactory() {
//        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
//        MqttConnectOptions options = new MqttConnectOptions();
//        options.setServerURIs(new String[]{mqttProperties.getHost()});
//        options.setUserName(mqttProperties.getUsername());
//        options.setPassword(mqttProperties.getPassword().toCharArray());
//        options.setCleanSession(mqttProperties.isCleanSession());
//        factory.setConnectionOptions(options);
//        return factory;
//    }

    // publisher

//    @Bean
//    public IntegrationFlow mqttOutFlow() {
//        //console input
        return IntegrationFlows.from(CharacterStreamReadingMessageSource.stdin(),
                e -> e.poller(Pollers.fixedDelay(1000)))
                .transform(p -> p + " sent to MQTT")
                .handle(mqttOutbound())
                .get();
//        return IntegrationFlows.from(outChannelMqtt())
//                .handle(mqttOutbound())
//                .get();
//    }

//    @Primary
//    @Bean
//    public MessageChannel outChannelMqtt() {
//        return new DirectChannel();
//    }

//    @Bean
//    public MessageHandler mqttOutbound() {
//        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getPublisher(), mqttClientFactory());
//        messageHandler.setAsync(true);
//        messageHandler.setDefaultTopic(mqttProperties.getTopic());
//        return messageHandler;
//    }

    // consumer

//    @Bean
//    public IntegrationFlow mqttInFlow() {
//        return IntegrationFlows.from(mqttInbound())
                .transform(p -> p + ", received from MQTT")
                .handle(logger())
//                .handle(accephandler())
//                .get();
//    }

//    @Bean
   这里注入处理逻辑服务
//    public MessageHandler accephandler() {
//        return new MessageHandler() {
//            @Override
//            public void handleMessage(Message<?> message) throws MessagingException {
//                Optional optional = Optional.ofNullable(message.getPayload());
//                if (optional.isPresent()) {
//                    System.out.println(message.getPayload());
//                } else {
//                    log.info("my" + message.getHeaders());
//                }
//
//            }
//
//        };
//    }


//    private LoggingHandler logger() {
//        LoggingHandler loggingHandler = new LoggingHandler("INFO");
//        loggingHandler.setLoggerName("siSample");
//        return loggingHandler;
//    }


    @Bean
    public MqttClient mqttClient() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{mqttProperties.getHost()});
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        options.setCleanSession(mqttProperties.isCleanSession());
        options.setAutomaticReconnect(true);
        options.setMaxReconnectDelay(1000);
        MqttClient client = null;
        try {
            String clientId = "clientId" + System.currentTimeMillis();
            client = new MqttClient(mqttProperties.getHost(), clientId, new MemoryPersistence());
            if (!client.isConnected()) {
                client.connect(options);
                log.info("================>>>MQTT连接成功<<======================");
            } else {// 这里的逻辑是如果连接不成功就重新连接
                client.disconnect();
                client.connect(options);
                log.info("===================>>>MQTT断连成功<<<======================");
            }
            //订阅主题
            client.subscribe(mqttProperties.getTopic(), mqttProperties.getQos());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }


}
PushCallback
package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Component
@Slf4j
public class PushCallback<component> implements MqttCallback {
    @Autowired
    MqttProperties mqttProperties;
    @Autowired
    MqttClient mqttClient;

    @PostConstruct
    public void init() {
        mqttClient.setCallback(this);
    }


    @Override
    public void connectionLost(Throwable throwable) {
        //失去连接
        //在此处重连
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{mqttProperties.getHost()});
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        options.setCleanSession(mqttProperties.isCleanSession());
        mqttClient.setCallback(this);
        while (!mqttClient.isConnected()) {
            try {
                mqttClient.connect(options);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        //订阅主题
        try {
            mqttClient.subscribe(mqttProperties.getTopic(), mqttProperties.getQos());
        } catch (MqttException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
        log.info("============》》接收消息主题 : " + topic);
        log.info("============》》接收消息Qos : " + message.getQos());
        log.info("============》》是否重复消息? : " + message.isDuplicate());
        log.info("============》》接收消息内容原始内容 : " + new String(message.getPayload()));
        log.info("============》》接收消息内容GB2312 : " + new String(message.getPayload(), "GB2312"));
        log.info("============》》接收消息内容UTF-8 : " + new String(message.getPayload(), "UTF-8"));

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("pushComplete==============>>>" + token.isComplete());
    }


}

测试

package com.example.demo.controller;

import com.example.demo.config.MqttProperties;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

@RestController
public class TestController {

    @Autowired
    MqttClient mqttClient;
    @Autowired
    MqttProperties mqttProperties;

    @RequestMapping("/test")
    public String tets1() {
        MqttMessage message = new MqttMessage();
        message.setQos(2);
        message.setRetained(false);
        message.setPayload("pushMessage.getBytes()".getBytes(StandardCharsets.UTF_8));
        if (!mqttClient.isConnected()) {
            //连接断开
            try {
                mqttClient.connect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
            try {
                mqttClient.subscribe(mqttProperties.getTopic(), mqttProperties.getQos());
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        MqttTopic mTopic = mqttClient.getTopic("/eeeee");
        MqttDeliveryToken token;
        try {
            token = mTopic.publish(message);
            token.waitForCompletion();
        } catch (MqttPersistenceException e) {
            e.printStackTrace();
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return "2";
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值