物联网 基于netty构建mqtt服务demo演示

物联网 基于netty构建mqtt服务demo演示

简述

基于Netty实现轻量级MQTT协议,利用了Netty的异步、非阻塞特性,将MQTT协议的核心能力(连接管理、消息路由、心跳保活等)进行模块化构建

基于Netty的MQTT服务

  • 连接接入:

通过EventLoopGroup(Boss & Worker)模型高效处理网络I/O,实现单机数万至百万连接的承载

  • 协议编解码:

定义MqttDecoder/Encoder解析编码MQTT报文。Netty的ChannelPipeline可灵活配置编解码器处理CONTROL报文

  • 核心处理:

在ChannelHandler中实现核心逻辑

复制代码
- 会话与状态管理:
>  管理客户端连接(如心跳超时检测),维护订阅树和消息缓存(Pending Messages)

- 消息路由:
> 为PUBLISH/SUBSCRIBE报文,实现高性能通配符匹配,将消息高效投递至订阅者

- QoS保证:
> 支持MQTT服务质量等级,确保消息的可靠投递

- 保留与遗嘱消息:
> 实现对持久会话的断线重连自动恢复,以及保留/遗嘱消息的处理
  • 存储扩展:

根据业务需求,往往需要将上述(会话、订阅、消息)数据进行持久化或使用高性能缓存(如Redis)

源码

https://gitee.com/kcnf-iot/iot-sample/tree/master/netty/netty-sample-01

添加pom依赖

复制代码
<dependencies>
    <!-- Netty 核心依赖 -->
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
    </dependency>
</dependencies>

项目目录结构

启动类 代码

复制代码
package com.jysemel.iot;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;


public class MqttServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 启用TCP的KeepAlive,探测死连接
                    .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加心跳检测:60秒无读事件触发IdleStateEvent
                            pipeline.addLast("idleStateHandler", new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                            // 添加MQTT解码器,指定最大报文长度为 65536 字节
                            pipeline.addLast("mqttDecoder", new MqttDecoder(64 * 1024));
                            // 添加MQTT编码器
                            pipeline.addLast("mqttEncoder", MqttEncoder.INSTANCE);
                            // 添加业务处理器
                            pipeline.addLast("mqttServerHandler", new MqttServerHandler());
                        }
                    });
            // 绑定1883端口并启动
            ChannelFuture channelFuture = serverBootstrap.bind(1883).sync();
            System.out.println("🚀 Netty MQTT Broker 启动成功,端口: 1883");
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

测试结果

相关推荐
小嘉丶学长1 天前
Day14 · 字典与集合
java·开发语言·网络·python·学习·1024程序员节
迪菲赫尔曼1 天前
【基础篇 11】把官方源码放到服务器:版本、解压层级和安装位置,一次弄清楚
运维·服务器·开发语言·人工智能·python·yolo·目标检测
chari克里1 天前
QT5.15.2 + msvc2022部署全流程说明(windows可联网环境)
开发语言·c++·qt
Hello.Reader1 天前
tsrs 技术解析用 Rust 移植 TypeScript 7,类型检查还能怎样提速?
开发语言·rust·typescript
透明的玻璃杯1 天前
VS2015+QT 多线程
开发语言·qt
码匠许师傅1 天前
【C++三方组件】mbedTLS:面向嵌入式的轻量 TLS
开发语言·c++
迪菲赫尔曼1 天前
【基础篇 12】把环境与源码接起来:检查 GPU,再安装服务器上的项目
运维·服务器·开发语言·人工智能·python·yolo·目标检测
2601_962885721 天前
2026 Python 股票数据接口选型指南(横评 + 决策树)
开发语言·python·区块链
Evand J1 天前
【PMSM例程4】PMSM电阻辨识与模型补偿EKF,MATLAB例程。附下载链接,包运行成功
开发语言·matlab·电机·ekf·卡尔曼·pmsm
王仔小奶1 天前
Rust 正在接管金融圈?深度拆解一份高薪 FinTech 岗位 JD
开发语言·金融·rust