SpringBoot项目接入MQTT协议

mqtt是一种类似于mq的通讯技术

1、mqtt服务端搭建

创建docker网络

docker network create --driver bridge --subnet 172.18.0.0/24 --gateway 172.18.0.1 emqx-net

创建容器

docker run -d \
    --name emqx1 \
    -e "EMQX_NODE_NAME=emqx@172.18.0.2" \
    --network emqx-net \
        --ip 172.18.0.2 \
    --network-alias 172.18.0.2 \
    -p 1883:1883 \
    -p 8083:8083 \
    -p 8084:8084 \
    -p 8883:8883 \
    -p 18083:18083 \
    emqx/emqx:5.4.1
        
        
docker run -d \
 --name emqx2 \
     --ip 172.18.0.3 \
 -e "EMQX_NODE_NAME=emqx@172.18.0.3" \
 --network emqx-net \
 --network-alias 172.18.0.3 \
 emqx/emqx:5.4.1
     
     
docker run -d \
 --name emqx3 \
     --ip 172.18.0.4 \
 -e "EMQX_NODE_NAME=emqx@172.18.0.4" \
 --network emqx-net \
 --network-alias 172.18.0.4 \
 emqx/emqx:5.4.1

服务节点注册

docker exec -it emqx2 \
emqx ctl cluster join emqx@172.18.0.2


docker exec -it emqx3 \
emqx ctl cluster join emqx@172.18.0.2

2、创建springboot项目,并增加mqtt依赖

依赖引入

<dependency>
    <groupId>com.hivemq</groupId>
    <artifactId>hivemq-mqtt-client</artifactId>
    <version>1.3.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>

创建连接器

@Configuration
public class VideoConfig implements MqttClientDisconnectedListener, MqttClientConnectedListener {
    static Logger logger = LoggerFactory.getLogger(VideoConfig.class);

    @Value("${mqtt.server.url:192.168.31.47}")
    private String serverUrl;//mqtt地址
    @Value("${mqtt.server.port:1883}")
    private Integer serverPort;//mqtt地址
    @Value("${mqtt.server.username}")
    private String serverUserName;//mqtt账号(测试默认没有)
    @Value("${mqtt.server.password}")
    private String serverPassWord;//mqtt密码(测试默认没有)

    @Autowired
    private DefautMqttConsumerListener defautMqttConsumerListener;

    @Bean
    public Mqtt3AsyncClient mqtt3AsyncClient(){
        String clientId = String.format("%d%s", TimeUtil.getCurrentInMillis(), RandomUtil.getRandomStr(10));
        Mqtt3ClientBuilder mqttClientBuilder = Mqtt3Client.builder();
        Mqtt3AsyncClient mqttClient = mqttClientBuilder
                .identifier(clientId)
                .serverHost(serverUrl)
                .serverPort(serverPort)
                .addConnectedListener(this)
                .addDisconnectedListener(this)
                .build().toAsync();
        mqttClient.connect();
        mqttClient.connectWith()
                .keepAlive(60)
                .willPublish()
                .topic("/")
                .applyWillPublish()
                .simpleAuth()
                .username(serverUserName)
                .password(serverPassWord.getBytes())
                .applySimpleAuth()
                .send()
                .whenCompleteAsync((connAck, throwable) -> {
                    Mqtt3ConnAckReturnCode returnCode = connAck.getReturnCode();
                    logger.info("mqtt connect result: {}", returnCode);
                    if (throwable != null) {
                        logger.error("connectWith error , throwable :"+throwable);
                    }
                });
        return mqttClient;
    }

	/**
	*连接成功回调后 监听mqtt消息
	**/
    @Override
    public void onConnected(MqttClientConnectedContext mqttClientConnectedContext) {
        String subscribedTopic ="+/reply";//+表示匹配一个信息
        mqtt3AsyncClient().subscribeWith()
        .topicFilter(subscribedTopic)
        .callback(defautMqttConsumerListener)
        .send()
        .whenComplete((subAck, throwable) -> {
            if (throwable != null) {
                logger.error("Handle failure to subscribe", throwable);
            } else {
                logger.info("successful subscription: " + subscribedTopic);
            }
        });
    }

	/**
	*连接关闭回调重新创建连接
	**/
    @Override
    public void onDisconnected(MqttClientDisconnectedContext mqttClientDisconnectedContext) {
        final Mqtt3ClientDisconnectedContext context = (Mqtt3ClientDisconnectedContext) mqttClientDisconnectedContext;
            try {
                context.getReconnector()
                        .connectWith()
                        .simpleAuth()
                        .username(serverUserName)
                        .password(serverPassWord.getBytes())
                        .applySimpleAuth()
                        .applyConnect()
                        .reconnect(true)
                        .delay(new Random().nextInt(100), TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                logger.error("reconnect:" + e.getMessage(), e);
            }
    }
}

监听器

@Component
public class DefautMqttConsumerListener implements Consumer<Mqtt3Publish> {
    private static final Logger logger = LoggerFactory.getLogger(DefautMqttConsumerListener.class);
    

    @Override
    public void accept(Mqtt3Publish mqttPublish) {
          String topic = mqttPublish.getTopic().toString();
          byte[] msg = mqttPublish.getPayloadAsBytes();
          String msgJson = new String(msg);
          logger.info("mqtt listener topic :{} ,msg:{}" ,topic, msgJson);
            
    }

}

消息发送

public void sendMqttMsg(String topic, MqttQos qos, String msg){
		mqtt3AsyncClient.publishWith()
				.topic(topic)
				.payload(msg.getBytes())
				.qos(Optional.ofNullable(qos).orElse(MqttQos.AT_LEAST_ONCE))
				.retain(false)
				.send()
				.whenComplete((result, throwable) -> {
					logger.info("sendMqttMsg to video, topic : {} , body : {}",topic,body);
					if (throwable != null) {
						logger.error("transfer failed , throwable :{}",throwable);
					}
				});
	}

3、MQTT工具

下载地址:https://mqttx.app/zh/downloads
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

QOS

分为3级,0表示发一次,意味着消息可能会丢失;1表示至少发一次,意味着消息可能会收到多次;2表示保证一次,但是越高性能越低,可以根据自己业务进行选择

topic

类似于rocketmq的topic,也类似于rabbitmq的routingKey,mqtt的topic同样也是消息收发的引导,监听时 + 号,表示匹配 任意 / 号中间的任何数据,# 号表示多个数据 包含了 / 号后边多个

  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MQTT(Message Queue Telemetry Transport)是一种轻量级的消息传输协议,它可以在不同的设备之间进行低延迟、低能耗的通信。在Spring Boot中,可以通过使用Spring Integration来实现MQTT协议接入。 以下是基于Spring Boot设计并实现MQTT协议接入的步骤: 1. 添加依赖:在pom.xml文件中添加spring-integration-mqtt和Eclipse Paho MQTT客户端库的依赖。 ```xml <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> <version>5.5.0</version> </dependency> <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency> ``` 2. 配置MQTT连接:在application.properties文件中添加MQTT连接的配置信息,包括MQTT服务器地址、端口、用户名和密码等。 ```properties mqtt.url=tcp://localhost:1883 mqtt.client.id=spring-boot-mqtt mqtt.username=your-username mqtt.password=your-password ``` 3. 实现MQTT消息处理器:创建一个处理MQTT消息的消息处理器类,用于接收和处理MQTT消息。可以实现MessageHandler接口,覆盖handleMessage方法,处理接收到的消息。 ```java @Component public class MqttMessageHandler implements MessageHandler { @Override public void handleMessage(Message<?> message) throws MessagingException { String payload = (String) message.getPayload(); System.out.println("Received message: " + payload); } } ``` 4. 配置MQTT连接工厂和消息适配器:创建一个MQTT连接工厂,并使用它来创建一个MQTT消息适配器,将消息适配器配置为使用上面创建的消息处理器处理接收到的消息。 ```java @Configuration @EnableIntegration public class MqttConfig { @Value("${mqtt.url}") private String mqttUrl; @Value("${mqtt.client.id}") private String mqttClientId; @Value("${mqtt.username}") private String mqttUsername; @Value("${mqtt.password}") private String mqttPassword; @Bean public MqttConnectOptions mqttConnectOptions() { MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(mqttUsername); options.setPassword(mqttPassword.toCharArray()); return options; } @Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setConnectionOptions(mqttConnectOptions()); return factory; } @Bean public MessageChannel mqttInputChannel() { return new DirectChannel(); } @Bean public MessageProducer inbound() { MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(mqttUrl, mqttClientId, mqttClientFactory(), "topic1", "topic2"); adapter.setCompletionTimeout(5000); adapter.setConverter(new DefaultPahoMessageConverter()); adapter.setQos(1); adapter.setOutputChannel(mqttInputChannel()); return adapter; } @Bean public IntegrationFlow mqttInFlow() { return IntegrationFlows.from(mqttInputChannel()) .handle(mqttMessageHandler()) .get(); } @Bean public MqttMessageHandler mqttMessageHandler() { return new MqttMessageHandler(); } } ``` 5. 发布MQTT消息:可以使用MqttPahoMessageHandler类来发布MQTT消息。可以注入MqttPahoClientFactory和MessageChannel,并使用它们创建和发送MQTT消息。 ```java @Service public class MqttPublisher { @Autowired private MqttPahoClientFactory mqttClientFactory; @Autowired private MessageChannel mqttOutputChannel; public void publish(String topic, String payload) { MqttPahoMessageHandler handler = new MqttPahoMessageHandler("publisher-" + UUID.randomUUID(), mqttClientFactory); handler.setAsync(true); handler.setDefaultTopic(topic); handler.setDefaultQos(1); handler.setDefaultRetained(false); handler.setAsyncEvents(false); handler.setAsync(true); handler.setChannel(mqttOutputChannel); handler.handleMessage(MessageBuilder.withPayload(payload).build()); } } ``` 以上就是基于Spring Boot设计并实现MQTT协议接入的步骤。通过这些步骤,可以实现在Spring Boot应用中使用MQTT协议进行消息传输。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值