springboot整合netty-mqtt-client实现Mqtt消息的订阅和发布示例

 更新时间:2022年03月16日 14:16:28   作者:行云的逆袭  
本文主要介绍了springboot整合netty-mqtt-client实现Mqtt消息的订阅和发布示例,文中根据实例编码详细介绍的十分详尽,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

1.添加依赖

<dependency>
    <groupId>org.jetlinks</groupId>
    <artifactId>netty-mqtt-client</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

2.源码

application.yml

#mqtt配置
mqtt:
  username: admin
  password: 123456
  #推送信息的连接地址
  url: localhost
  port: 1884
  #默认发送的主题
  defaultTopic: topic
  #clientid
  clientId: client
  #连接超时时间 单位为秒
  completionTimeout: 300
  #设置会话心跳时间 单位为秒
  keepAliveInterval: 20

MqttProperties.java

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

@Data
@ConfigurationProperties(prefix = "mqtt")
public class MqttProperties {

	private String username;
	private String password;
	private String url;
	private int port;
	private String clientId;
	private String defaultTopic;
	private int completionTimeout;
	private int keepAliveInterval;
}

MqttConfig.java

import com.xingyun.netty.mqtt.prop.MqttProperties;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.AllArgsConstructor;
import org.jetlinks.mqtt.client.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(MqttProperties.class)
public class MqttConfig {

    private final MqttProperties mqttProperties;

    @Bean
    public MqttClientConfig getMqttClientConfig() {
        MqttClientConfig mqttClientConfig = new MqttClientConfig();
        mqttClientConfig.setClientId(mqttProperties.getClientId());
        mqttClientConfig.setUsername(mqttProperties.getClientId());
        mqttClientConfig.setPassword(mqttProperties.getPassword());
        /*mqttClientConfig.setTimeoutSeconds(mqttProperties.getCompletionTimeout());
        mqttClientConfig.setRetryInterval(mqttProperties.getKeepAliveInterval());
        mqttClientConfig.setProtocolVersion(MqttVersion.MQTT_3_1_1);
        mqttClientConfig.setReconnect(true);*/
        return mqttClientConfig;
    }

    @Bean
    public MqttClient getMqttClient(){
        EventLoopGroup loop = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);

        MqttClient mqttClient = new MqttClientImpl(getMqttClientConfig(),null);
        mqttClient.setEventLoop(loop);
        mqttClient.setCallback(getMqttClientCallback());
        mqttClient.connect(mqttProperties.getUrl(), mqttProperties.getPort()).addListener(future -> {
            if (future.isSuccess()){
                System.out.println("mqtt客户端已建立连接");
                //#为多层通配符,+为单层通配符
                mqttClient.on("#",getMqttHandler());
            }
        });
        return mqttClient;
    }

    @Bean
    public MqttHandler getMqttHandler(){
        return (topic,payload) ->  {
            System.out.println("消息主题:" + topic);
            System.out.println("消息内容:" + payload);
        };
    }

    @Bean
    public MqttClientCallback getMqttClientCallback(){
        return new MqttClientCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                cause.printStackTrace();
            }

            @Override
            public void onSuccessfulReconnect() {
                System.out.println("客户端已重连");
            }
        };
    }

}

3.运行测试

客户端利用不同主题,发送消息

在这里插入图片描述

控制台

消息主题:testTopic/001
消息内容:PooledSlicedByteBuf(ridx: 0, widx: 15, cap: 15/15, unwrapped: PooledUnsafeDirectByteBuf(ridx: 32, widx: 32, cap: 512))
消息主题:testTopic/001
消息内容:PooledSlicedByteBuf(ridx: 0, widx: 15, cap: 15/15, unwrapped: PooledUnsafeDirectByteBuf(ridx: 32, widx: 32, cap: 512))
消息主题:test/sub/001
消息内容:PooledSlicedByteBuf(ridx: 0, widx: 15, cap: 15/15, unwrapped: PooledUnsafeDirectByteBuf(ridx: 31, widx: 31, cap: 496))
消息主题:test1
消息内容:PooledSlicedByteBuf(ridx: 0, widx: 15, cap: 15/15, unwrapped: PooledUnsafeDirectByteBuf(ridx: 24, widx: 24, cap: 496))

单元测试发布消息
MqttSeviceDemo.java

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.jetlinks.mqtt.client.MqttClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MqttSeviceDemo {

    @Autowired
    private MqttClient mqttClient;

    @Test
    public void publishMessage(){
        String test = "I am client9527";
        byte[] bytes = test.getBytes();
        ByteBuf byteBuf = Unpooled.copiedBuffer(bytes);
        mqttClient.publish("test/pub/001",byteBuf);
        System.out.println("消息已发布");
    }

}

客户端订阅到消息

在这里插入图片描述

 到此这篇关于springboot整合netty-mqtt-client实现Mqtt消息的订阅和发布示例的文章就介绍到这了,更多相关springboot Mqtt消息订阅和发布内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java网络编程之UDP网络通信详解

    Java网络编程之UDP网络通信详解

    这篇文章主要为大家详细介绍了Java网络编程中的UDP网络通信的原理与实现,文中的示例代码讲解详细,具有一定的借鉴价值,需要的可以参考一下
    2022-09-09
  • SpringBoot 中实现跨域的5种方式小结

    SpringBoot 中实现跨域的5种方式小结

    这篇文章主要介绍了SpringBoot 中实现跨域的5种方式小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • java实现基于TCP协议网络socket编程(C/S通信)

    java实现基于TCP协议网络socket编程(C/S通信)

    这篇文章主要介绍了java实现基于TCP协议网络socket编程(C/S通信),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • Spring aop 如何通过获取代理对象实现事务切换

    Spring aop 如何通过获取代理对象实现事务切换

    这篇文章主要介绍了Spring aop 如何通过获取代理对象实现事务切换的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 详解Mybatis内的mapper方法为何不能重载

    详解Mybatis内的mapper方法为何不能重载

    这篇文章主要介绍了详解Mybatis内的mapper方法为何不能重载,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • SpringMVC数据输出相关知识总结

    SpringMVC数据输出相关知识总结

    今天带大家学习SpringMVC的相关知识,文中对SpringMVC数据输出作了非常详细的代码示例,对正在学习的小伙伴们很有帮助,需要的朋友可以参考下
    2021-06-06
  • JPA 加锁机制及@Version版本控制方式

    JPA 加锁机制及@Version版本控制方式

    这篇文章主要介绍了JPA 加锁机制及@Version版本控制方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • Java枚举类使用Lombok方式

    Java枚举类使用Lombok方式

    这篇文章主要介绍了Java枚举类使用Lombok方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • 详解SpringBoot中@PostMapping注解的用法

    详解SpringBoot中@PostMapping注解的用法

    在SpringBoot中,我们经常需要编写RESTful Web服务,以便于客户端与服务器之间的通信,@PostMapping注解可以让我们更方便地编写POST请求处理方法,在本文中,我们将介绍@PostMapping注解的作用、原理,以及如何在SpringBoot应用程序中使用它
    2023-06-06
  • Java线程编程中Thread类的基础学习教程

    Java线程编程中Thread类的基础学习教程

    这篇文章主要介绍了Java线程编程中Thread类的基础学习教程,Thread类包含诸多操作线程的方法,非常重要,需要的朋友可以参考下
    2015-12-12

最新评论