spring boot+netty 搭建MQTT broken

news2024/11/23 15:39:31

一、项目结构
在这里插入图片描述
二、安装依赖

<!--      netty包  -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.75.Final</version>
        </dependency>
        <!--   常用JSON工具包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.80</version>
        </dependency>
        <!--mqtt服务端-->
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mqtt</artifactId>
        </dependency>

三、配置文件

server:
  port: 8880
netty:
  mqtt:
    port: 1883
#    mqtt账号
    username: admin
#mqtt密码
    password: 123456
# 日记配置
logging:
  level:
    # 开启debug日记打印
    com.hyx: debug

四、新建具体类
1、新建BootNettyMqttMsgBack类

package com.example.springnettymqtt.MQTTServer.callback;

import com.example.springnettymqtt.MQTTServer.config.MQTTServerProperties;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.netty.channel.ChannelId;
import io.netty.handler.codec.mqtt.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.example.springnettymqtt.MQTTServer.channel.MQTTDeviceManerger.MQTTdeviceAdd;
import static com.example.springnettymqtt.MQTTServer.channel.MQTTDeviceManerger.MQTTdeviceRemove;
import static com.example.springnettymqtt.MQTTServer.server.impl.MQTTServer.*;


@Component
@RequiredArgsConstructor
public class BootNettyMqttMsgBack {
    private static final Logger log =  LoggerFactory.getLogger(BootNettyMqttMsgBack.class);
    private final MQTTServerProperties MQTTserverProperties;

    /**
     * 	确认连接请求
     * @param channel
     * @param mqttMessage
     */
    public void connack (Channel channel, MqttMessage mqttMessage) {
        MqttConnectMessage mqttConnectMessage = (MqttConnectMessage) mqttMessage;
        MqttFixedHeader mqttFixedHeaderInfo = mqttConnectMessage.fixedHeader();
        MqttConnectVariableHeader mqttConnectVariableHeaderInfo = mqttConnectMessage.variableHeader();

        //	构建返回报文, 可变报头
        MqttConnAckVariableHeader mqttConnAckVariableHeaderBack = new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_ACCEPTED, mqttConnectVariableHeaderInfo.isCleanSession());
        //	构建返回报文, 固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.CONNACK,mqttFixedHeaderInfo.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeaderInfo.isRetain(), 0x02);
        //	构建CONNACK消息体
        MqttConnAckMessage connAck = new MqttConnAckMessage(mqttFixedHeaderBack, mqttConnAckVariableHeaderBack);
        //log.info("back--"+connAck.toString());
        log.debug("设备上线,channelId:{}", channel.id());
        MQTTdeviceAdd(channel);
        channel.writeAndFlush(connAck);
    }
    public void disconnack (Channel channel, MqttMessage mqttMessage) {
        MqttConnectMessage mqttConnectMessage = (MqttConnectMessage) mqttMessage;
        MqttFixedHeader mqttFixedHeaderInfo = mqttConnectMessage.fixedHeader();
        MqttConnectVariableHeader mqttConnectVariableHeaderInfo = mqttConnectMessage.variableHeader();
        //	构建返回报文, 可变报头
        MqttConnAckVariableHeader mqttConnAckVariableHeaderBack = new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_BANNED, mqttConnectVariableHeaderInfo.isCleanSession());
        //	构建返回报文, 固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.DISCONNECT,mqttFixedHeaderInfo.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeaderInfo.isRetain(), 0x02);
        //	构建CONNACK消息体
        MqttConnAckMessage connAck = new MqttConnAckMessage(mqttFixedHeaderBack, mqttConnAckVariableHeaderBack);
        //log.info("back--"+connAck.toString());
        channel.writeAndFlush(connAck);
        log.debug("设备下线,channelId:{}", channel.id());
        MQTTdeviceRemove(channel);
    }

    /**
     * 	根据qos发布确认
     * @param channel
     * @param mqttMessage
     */
    public  void puback (Channel channel, MqttMessage mqttMessage) {
        MqttPublishMessage mqttPublishMessage = (MqttPublishMessage) mqttMessage;
        MqttFixedHeader mqttFixedHeaderInfo = mqttPublishMessage.fixedHeader();
        MqttQoS qos =  mqttFixedHeaderInfo.qosLevel();
        //注意:	readableBytes会改变写指针位置,使后续推送数据时,读取数据为空,需要重置	读指针
        byte[] headBytes = new byte[mqttPublishMessage.payload().readableBytes()];
        mqttPublishMessage.payload().readBytes(headBytes);
        String data = new String(headBytes);
        System.out.println("publish data-->"+data);
        //重置读取的指针
        mqttPublishMessage.payload().resetReaderIndex();
        switch (qos) {
            case AT_MOST_ONCE: 		//	至多一次
                //推送到订阅的客户端
                subscribSend(mqttMessage);
                break;
            case AT_LEAST_ONCE:		//	至少一次
                //	构建返回报文, 可变报头
                MqttMessageIdVariableHeader mqttMessageIdVariableHeaderBack = MqttMessageIdVariableHeader.from(mqttPublishMessage.variableHeader().packetId());
                //	构建返回报文, 固定报头
                MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.PUBACK,mqttFixedHeaderInfo.isDup(), MqttQoS.AT_MOST_ONCE, mqttFixedHeaderInfo.isRetain(), 0x02);
                //	构建PUBACK消息体
                MqttPubAckMessage pubAck = new MqttPubAckMessage(mqttFixedHeaderBack, mqttMessageIdVariableHeaderBack);
                log.info("back--"+pubAck.toString());
                channel.writeAndFlush(pubAck);
                //推送到订阅的客户端
                subscribSend(mqttMessage);
                break;
            case EXACTLY_ONCE:		//	刚好一次
                //	构建返回报文, 固定报头
                MqttFixedHeader mqttFixedHeaderBack2 = new MqttFixedHeader(MqttMessageType.PUBREC,false, MqttQoS.AT_LEAST_ONCE,false,0x02);
                //	构建返回报文, 可变报头
                MqttMessageIdVariableHeader mqttMessageIdVariableHeaderBack2 = MqttMessageIdVariableHeader.from(mqttPublishMessage.variableHeader().packetId());
                MqttMessage mqttMessageBack = new MqttMessage(mqttFixedHeaderBack2,mqttMessageIdVariableHeaderBack2);
                //服务端收到publis的QoS2的消息之后,服务端需要保存一个msgid的记录,并且进入一个状态,
                // 即之后不管来了几个这个msgid的消息,都不管他,认为是重复的,丢弃。
                //接收到publish的QoS2消息之后,不能马上投递给上层,而是在本地做持久化,将消息保存起来。
                int mqttMessageId=mqttPublishMessage.variableHeader().packetId();
                if(!mqttMessageIdMap.containsKey(mqttMessageId)){
                    //不存在此消息,将此消息暂存
                    mqttMessageIdMap.put(mqttMessageId, mqttMessage);
                    log.info("消息ID"+mqttMessageId+"-->Qos2级别消息,消息缓存");
                }else{
                    //重复发送消息,直接返回
                    log.info(mqttPublishMessage.variableHeader().packetId()+"消息重复:"+mqttPublishMessage.fixedHeader().isDup());
                    return;
                }
                channel.writeAndFlush(mqttMessageBack);
                break;
            default:
                break;
        }
    }

    /**
     * 	发布完成 qos2
     * @param channel
     * @param mqttMessage
     */
    public  void pubcomp (Channel channel, MqttMessage mqttMessage) {
        MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage.variableHeader();
        //	构建返回报文, 固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.PUBCOMP,false, MqttQoS.AT_MOST_ONCE,false,0x02);
        //	构建返回报文, 可变报头
        MqttMessageIdVariableHeader mqttMessageIdVariableHeaderBack = MqttMessageIdVariableHeader.from(messageIdVariableHeader.messageId());
        MqttMessage mqttMessageBack = new MqttMessage(mqttFixedHeaderBack,mqttMessageIdVariableHeaderBack);
        //log.info("back--"+mqttMessageBack.toString());
        channel.writeAndFlush(mqttMessageBack);
    }

    /**
     * 	订阅确认
     * @param channel
     * @param mqttMessage
     */
    public  void suback(Channel channel, MqttMessage mqttMessage) {
        MqttSubscribeMessage mqttSubscribeMessage = (MqttSubscribeMessage) mqttMessage;
        MqttMessageIdVariableHeader messageIdVariableHeader = mqttSubscribeMessage.variableHeader();
        //	构建返回报文, 可变报头
        MqttMessageIdVariableHeader variableHeaderBack = MqttMessageIdVariableHeader.from(messageIdVariableHeader.messageId());
        Set<String> topics = mqttSubscribeMessage.payload().topicSubscriptions().stream().map(mqttTopicSubscription -> mqttTopicSubscription.topicName()).collect(Collectors.toSet());
        //log.info(topics.toString());
        List<Integer> grantedQoSLevels = new ArrayList<>(topics.size());
        for (int i = 0; i < topics.size(); i++) {
            grantedQoSLevels.add(mqttSubscribeMessage.payload().topicSubscriptions().get(i).qualityOfService().value());
        }
        //	构建返回报文	有效负载
        MqttSubAckPayload payloadBack = new MqttSubAckPayload(grantedQoSLevels);
        //	构建返回报文	固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_MOST_ONCE, false, 2+topics.size());
        //	构建返回报文	订阅确认
        MqttSubAckMessage subAck = new MqttSubAckMessage(mqttFixedHeaderBack,variableHeaderBack, payloadBack);
        channel.writeAndFlush(subAck);
    }

    /**
     * 	取消订阅确认
     * @param channel
     * @param mqttMessage
     */
    public  void unsuback(Channel channel, MqttMessage mqttMessage) {
        MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage.variableHeader();
        //	构建返回报文	可变报头
        MqttMessageIdVariableHeader variableHeaderBack = MqttMessageIdVariableHeader.from(messageIdVariableHeader.messageId());
        //	构建返回报文	固定报头
        MqttFixedHeader mqttFixedHeaderBack = new MqttFixedHeader(MqttMessageType.UNSUBACK, false, MqttQoS.AT_MOST_ONCE, false, 2);
        //	构建返回报文	取消订阅确认
        MqttUnsubAckMessage unSubAck = new MqttUnsubAckMessage(mqttFixedHeaderBack,variableHeaderBack);
        channel.writeAndFlush(unSubAck);
    }

    /**
     * 	心跳响应
     * @param channel
     * @param mqttMessage
     */
    public  void pingresp (Channel channel, MqttMessage mqttMessage) {
        //	心跳响应报文	11010000 00000000  固定报文
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0);
        MqttMessage mqttMessageBack = new MqttMessage(fixedHeader);
        channel.writeAndFlush(mqttMessageBack);
    }

    /**
     * 订阅推送
     */
    public  void subscribSend(MqttMessage mqttMessage){
        MqttPublishMessage mqttPublishMessage = (MqttPublishMessage) mqttMessage;
        Object obj=mqttMessage.variableHeader();
        MqttPublishVariableHeader variableHeader=(MqttPublishVariableHeader)obj;
        String topicName=variableHeader.topicName();
        int packetId=variableHeader.packetId();
        //固定消息头 注意此处的消息类型PUBLISH mqtt协议
        MqttFixedHeader FixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH,false, MqttQoS.AT_LEAST_ONCE,false,0);
        //可变消息头
        MqttPublishVariableHeader mqttPublishVariableHeader=new MqttPublishVariableHeader(topicName,packetId);
        //推送消息体
        MqttPublishMessage mqttPublishMessageResult=new MqttPublishMessage(FixedHeader,mqttPublishVariableHeader, mqttPublishMessage.content());
        log.info("推送地址————》"+topicName);
        if(subscribeMap.containsKey(topicName)){
            List<ChannelId> channelList=subscribeMap.get(topicName);
            for (int i = 0; i < channelList.size(); i++) {
                //订阅次此topic的Mqtt客户端搜到此消息,
                Channel channelSub=MQTTdeviceChannelGroup.find(channelList.get(i));
                //writeAndFlush会将ByteBuf的引用释放refCnt会减去1,使用retain加1
                mqttPublishMessageResult.retain();
                channelSub.writeAndFlush(mqttPublishMessageResult);
            }
            mqttPublishMessageResult.release();

        }
    }

    /**
     * 用户鉴权
     */
    public boolean authentication(MqttConnectPayload payload){

        String username=MQTTserverProperties.getUsername();
        String password=MQTTserverProperties.getPassword();
        //无账号或者无密码通过
        if(stringEmptyCheck(password)||stringEmptyCheck(username)){
            return true;
        }else {
            //消息中账号密码为空
            if(payload.passwordInBytes()==null||payload.userName()==null){
                return false;
            }
            String passwordAuthen=new String(payload.passwordInBytes());
            String usernameAuthen=payload.userName();
            if(password.equals(passwordAuthen)&&username.equals(usernameAuthen)){
                return true;
            }else {
                return false;
            }
        }
    }
    //判断字符字符为空
    private boolean stringEmptyCheck(String str){
        if(str==null||"".equals(str)){
            return true;
        }else {
            return false;
        }
    }
}

2、新建MqttChannelInit类

package com.example.springnettymqtt.MQTTServer.channel;

import com.example.springnettymqtt.MQTTServer.handler.MQTTMessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class MqttChannelInit extends ChannelInitializer<SocketChannel> {
    @Autowired
    private MQTTMessageHandler MQTTmessageHandler;

    @Override
    protected void initChannel(SocketChannel channel) {
        channel.pipeline()
                // 心跳时间
                .addLast("idle", new IdleStateHandler(600, 600, 1200, TimeUnit.SECONDS))
                .addLast("encoder", MqttEncoder.INSTANCE)
                .addLast("decoder", new MqttDecoder())
                .addLast(MQTTmessageHandler);
    }
}

3、新建MQTTDeviceManerger类

package com.example.springnettymqtt.MQTTServer.channel;

import lombok.extern.slf4j.Slf4j;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

import static com.example.springnettymqtt.MQTTServer.server.impl.MQTTServer.*;

@Slf4j
public class MQTTDeviceManerger {
    /**
     * 设备接入
     */
    public static void MQTTdeviceAdd(Channel channel) {
        if(!MQTTdeviceChannelGroup.contains(channel)) {
            MQTTdeviceChannelGroup.add(channel);
        }
    }
    /**
     * 设备移除和和订阅的topic
     */
    public static void MQTTdeviceRemove(Channel channel) {
        if(MQTTdeviceChannelGroup.contains(channel)) {
            MQTTdeviceChannelGroup.remove(channel);
            MQTTremoveDeviceChannelId(channel.id());
            //移除topic中的这个设备的chanelid
            for (Map.Entry<String, List<ChannelId>> listEntry : subscribeMap.entrySet()) {
                try {
                    if (listEntry.getValue().contains(channel.id())) {
                        listEntry.getValue().remove(channel.id());
                        log.info(channel.id() + "下线,topic:  " + listEntry.getKey() + "中移除此id");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void MQTTremoveDeviceChannelId(ChannelId channelId) {
        MQTTdeviceMap.entrySet().removeIf(item -> item.getValue().equals(channelId));
    }
}

4、新建配置类

package com.example.springnettymqtt.MQTTServer.config;

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

@Configuration
@ConfigurationProperties(prefix = MQTTServerProperties.MQTTPREFIX)
@Data
public class MQTTServerProperties {
    public static final String MQTTPREFIX = "netty.mqtt";

    /**
     * 服务器端口
     */
    private Integer port;

    /**
     * mqtt服务器用户名
     */
    private String username;

    /**
     * mqtt服务器密码
     */
    private String password;
}

5、新建MQTTMessageHandler类

package com.example.springnettymqtt.MQTTServer.handler;

import com.example.springnettymqtt.MQTTServer.callback.BootNettyMqttMsgBack;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import io.netty.channel.*;
import io.netty.handler.codec.mqtt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.example.springnettymqtt.MQTTServer.channel.MQTTDeviceManerger.MQTTdeviceRemove;
import static com.example.springnettymqtt.MQTTServer.server.impl.MQTTServer.*;

@Slf4j
@Component
@ChannelHandler.Sharable
@RequiredArgsConstructor
public class MQTTMessageHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private BootNettyMqttMsgBack bootNettyMqttMsgBack;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (null != msg) {
            MqttMessage mqttMessage = (MqttMessage) msg;
            log.info("info--"+mqttMessage.toString());
            MqttFixedHeader mqttFixedHeader = mqttMessage.fixedHeader();
            Channel channel = ctx.channel();
            if(mqttFixedHeader.messageType().equals(MqttMessageType.CONNECT)){
                //用户鉴权(配置文件中配置账号和密码,如果没有默认)
                log.warn("正在尝试鉴权");
                boolean authentag=  bootNettyMqttMsgBack.authentication((MqttConnectPayload)mqttMessage.payload());
                if(!authentag){
                    return;
                }
                //	在一个网络连接上,客户端只能发送一次CONNECT报文。服务端必须将客户端发送的第二个CONNECT报文当作协议违规处理并断开客户端的连接
                if(MQTTdeviceChannelGroup.contains(channel)){
                    //移除次设备channel和topic
                    bootNettyMqttMsgBack.disconnack(channel,mqttMessage);
                }
                //	to do 建议connect消息单独处理,用来对客户端进行认证管理等 这里直接返回一个CONNACK消息
                bootNettyMqttMsgBack.connack(channel, mqttMessage);
            }
            //对于没有鉴权的设备,请求不处理
            if(!MQTTdeviceChannelGroup.contains(channel)){
                log.warn(channel.id()+"无鉴权操作");
                return;
            }
            switch (mqttFixedHeader.messageType()){
                case PUBLISH:		//	客户端发布消息
                    //	PUBACK报文是对QoS 1等级的PUBLISH报文的响应
                    bootNettyMqttMsgBack.puback(channel, mqttMessage);
                    break;
                // PUBREL	Qos2级别消息,客户端返回
                case PUBREL:
                    //	PUBREL(客户端发给服务端)报文是对PUBREC(服务端发给客户端)报文的响应
                    //服务端收到pubrel之后,正式将消息投递给上层应用层。
                    MqttMessageIdVariableHeader VariableHeader=(MqttMessageIdVariableHeader)mqttMessage.variableHeader();
                    if(mqttMessageIdMap.containsKey(VariableHeader.messageId())) {
                        log.warn("移除消息缓存-->消息id"+VariableHeader.messageId());
                        bootNettyMqttMsgBack.subscribSend(mqttMessageIdMap.get(VariableHeader.messageId()));
                        bootNettyMqttMsgBack.pubcomp(channel, mqttMessage);
                        mqttMessageIdMap.remove(VariableHeader.messageId());
                    }else {
                        //后续多次收到REL消息,制作comp响应
                        bootNettyMqttMsgBack.pubcomp(channel, mqttMessage);
                    }
                    break;
                case SUBSCRIBE:		//	客户端订阅主题
                    //	客户端向服务端发送SUBSCRIBE报文用于创建一个或多个订阅,每个订阅注册客户端关心的一个或多个主题。
                    //	为了将应用消息转发给与那些订阅匹配的主题,服务端发送PUBLISH报文给客户端。
                    //	SUBSCRIBE报文也(为每个订阅)指定了最大的QoS等级,服务端根据这个发送应用消息给客户端
                    // 	to do
                    bootNettyMqttMsgBack.suback(channel, mqttMessage);
                    MqttSubscribePayload SubscribePayload=(MqttSubscribePayload) mqttMessage.payload();;
                    for (int i = 0; i < SubscribePayload.topicSubscriptions().size(); i++) {
                        String topicname=SubscribePayload.topicSubscriptions().get(i).topicName();
                        boolean tag=subscribeMap.containsKey(topicname);
                        if(tag){
                            List<ChannelId> channelIds=subscribeMap.get(topicname);
                            if(!channelIds.contains(channel.id())) {
                                channelIds.add(channel.id());
                            }else {
                                log.warn(channel.id()+"重复订阅");
                            }
                            subscribeMap.put(topicname, channelIds);
                        }else {
                            List<ChannelId> channelIds=new ArrayList<>();
                            channelIds.add(channel.id());
                            subscribeMap.put(topicname,channelIds);
                        }
                        log.info(channel.id()+"订阅地址————》"+topicname);
                    }


                    break;
                case UNSUBSCRIBE:	//	客户端取消订阅
                    //	客户端发送UNSUBSCRIBE报文给服务端,用于取消订阅主题
                    //	to do
                    bootNettyMqttMsgBack.unsuback(channel, mqttMessage);
                    Object Unsubscribe=mqttMessage.payload();
                    MqttUnsubscribePayload unsubscribePayload=(MqttUnsubscribePayload)Unsubscribe;
                    int len=unsubscribePayload.topics().size();
                    for (int i = 0; i < len; i++) {
                        String topicname=unsubscribePayload.topics().get(i);
                        boolean tag=subscribeMap.containsKey(topicname);
                        if(tag){
                            List<ChannelId> channelIds=subscribeMap.get(topicname);
                            channelIds.remove(channel.id());
                            subscribeMap.put(topicname,channelIds);
                        }else {
                            log.error("不存在订阅地址——>"+topicname);
                        }
                        log.info(channel.id()+"取消订阅地址————》"+topicname);
                    }

                    break;
                case PINGREQ:		//	客户端发起心跳
                    //	客户端发送PINGREQ报文给服务端的
                    //	在没有任何其它控制报文从客户端发给服务的时,告知服务端客户端还活着
                    //	请求服务端发送 响应确认它还活着,使用网络以确认网络连接没有断开
                    bootNettyMqttMsgBack.pingresp(channel, mqttMessage);
                    break;
                case DISCONNECT:	//	客户端主动断开连接
                    log.debug("设备下线,channelId:{}", channel.id());
                    MQTTdeviceRemove(channel);
                    //	DISCONNECT报文是客户端发给服务端的最后一个控制报文, 服务端必须验证所有的保留位都被设置为0
                    //	to do
                    break;
                default:
                    break;
            }
        }
        else {
            return;
        }
    }

    /**
     * 	从客户端收到新的数据、读取完成时调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws IOException {
    }

    /**
     * 	客户端与服务端第一次建立连接时执行 在channelActive方法之前执行
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    /**
     * 	客户端与服务端 断连时执行 channelInactive方法之后执行
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.warn(ctx.channel().id()+"连接断开");
        MQTTdeviceRemove(ctx.channel());
        super.channelUnregistered(ctx);

    }

    /**
     * 	当出现 Throwable 对象才会被调用,即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        log.warn(channel.id()+"连接异常断开。。。。。。。");
        MQTTdeviceRemove(ctx.channel());
        super.exceptionCaught(ctx, cause);
        if(channel.isActive()){
            ctx.close();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.debug("\n");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
    /**
     * 	服务端 当读超时时 会调用这个方法
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        ctx.close();
    }
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }
}

6、新建接口IMQTTServer及其实现类MQTTServer

package com.example.springnettymqtt.MQTTServer.server;

import javax.annotation.PreDestroy;

public interface IMQTTServer {
    /**
     * 主启动程序,初始化参数
     *
     * @throws Exception 初始化异常
     */
    void start() throws Exception;

    /**
     * 优雅的结束服务器
     *
     * @throws InterruptedException 提前中断异常
     */
    @PreDestroy
    void destroy() throws InterruptedException;
}

package com.example.springnettymqtt.MQTTServer.server.impl;

import com.example.springnettymqtt.MQTTServer.channel.MqttChannelInit;
import com.example.springnettymqtt.MQTTServer.config.MQTTServerProperties;
import com.example.springnettymqtt.MQTTServer.server.IMQTTServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@RequiredArgsConstructor
public class MQTTServer implements IMQTTServer {
    private final MqttChannelInit mqttChannelInit;

    private final MQTTServerProperties MQTTserverProperties;

    //保存接入的MQTT设备channel
    public static ChannelGroup MQTTdeviceChannelGroup;
    //保存订阅地址和chanelid,当推送数据时,会向此订阅地址的多个channel发送数据
    public static Map<String, List<ChannelId>> subscribeMap =new ConcurrentHashMap();
    //保存设备名称和通道编号,向设备发送消息可以通过名称找到通道
    public static ConcurrentHashMap<String, ChannelId> MQTTdeviceMap = new ConcurrentHashMap<>();
    //存放Qos2消息等级的消息ID,这里可使用redis之类的工具做缓存,为了简化配置,使用map暂存
    public static ConcurrentHashMap<Integer, MqttMessage> mqttMessageIdMap=new ConcurrentHashMap();
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Override
    public void start() {
        log.info("初始化 Mqttserver ...");
        bossGroup = new NioEventLoopGroup();
        workerGroup =  new NioEventLoopGroup();
        MQTTdeviceChannelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        this.MqttServer();
    }
    /**
     * 初始化
     */
    private void MqttServer() {
        try {
            new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel( NioServerSocketChannel.class )
                    .localAddress(new InetSocketAddress(MQTTserverProperties.getPort()))
                    // 配置 编码器、解码器、业务处理
                    .childHandler(mqttChannelInit)
                    // tcp缓冲区
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 将网络数据积累到一定的数量后,服务器端才发送出去,会造成一定的延迟。希望服务是低延迟的,建议将TCP_NODELAY设置为true
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    // 保持长连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 绑定端口,开始接收进来的连接
                    .bind().sync();
            log.info("MQTT服务启动成功!开始监听端口:{}", MQTTserverProperties.getPort());
        } catch (Exception e) {
            e.printStackTrace();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 销毁
     */
    @PreDestroy
    @Override
    public void destroy() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

7、新建启动类

package com.example.springnettymqtt.startServer;

import com.example.springnettymqtt.MQTTServer.server.impl.MQTTServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class StartSrver {

    @Autowired
    private MQTTServer mqttServer;
    @PostConstruct
    public void startNetty(){

        new Thread(() -> {
            try {
                mqttServer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1190303.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

双十一成交千万级!伊能静疗愈直播人-货-场洞察

近日&#xff0c;伊能静在小红书的疗愈直播火了。10月28日&#xff0c;小红书美护买手伊能静的第二场直播观看人数166万&#xff0c;粉丝人均观看时间12分52秒&#xff0c;11家在国内声量不大的国际品牌单品在直播间售罄。就此&#xff0c;也让我们看到了疗愈经济的可能性。 一…

clang插件对llvm源码插桩,分析函数调用日志(2)--google镜像

tick_plot__compile.ipynb clang插件对llvm源码插桩&#xff0c;分析函数调用日志(1) 分析 进出、链、出 df进出df[ df[tickKind].isin( [FuncEnter,FuncReturn] ) ]#代码中&#xff0c;只有在函数进入时&#xff0c;计算了链条长度 并写磁盘 df入df[ df[tickKind].isin…

linux如何实现免密登录

shigen日更文章的博客写手&#xff0c;擅长Java、python、vue、shell等编程语言和各种应用程序、脚本的开发。记录成长&#xff0c;分享认知&#xff0c;留住感动。 十一月是比较特殊的月份&#xff0c;因为很多云资源都是在这个时候过期&#xff0c;包括我自己买的云服务器。作…

安装pr提示VCRUNTIME140.dll丢失的修复方法,3个有效的方法

在学习和工作中&#xff0c;我们经常需要使用到PR和PS。然而&#xff0c;在安装这些软件时&#xff0c;有时会遇到一些错误提示&#xff0c;其中之一就是“VCRUNTIME140.dll丢失”&#xff0c;无法运行启动软件程序。那么&#xff0c;如何解决VCRUNTIME140.dll丢失的问题呢&…

无人机航迹规划:七种智能优化算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划--提供MATLAB代码

一、七种算法&#xff08;DBO、LO、SWO、COA、LSO、KOA、GRO&#xff09;简介 1、蜣螂优化算法DBO 蜣螂优化算法&#xff08;Dung beetle optimizer&#xff0c;DBO&#xff09;由Jiankai Xue和Bo Shen于2022年提出&#xff0c;该算法主要受蜣螂的滚球、跳舞、觅食、偷窃和繁…

栈的顺序存储实现(C语言)(数据结构与算法)

栈的顺序存储实现通常使用数组来完成。实现方法包括定义一个固定大小的数组&#xff0c;以及一个指向栈顶的指针。当元素入栈时&#xff0c;指针加一并将元素存储在相应位置&#xff1b;当元素出栈时&#xff0c;指针减一并返回相应位置的元素。 1. 顺序栈定义 #define MaxSi…

C++ 之多态(一)

什么是虚函数 在类的定义中&#xff0c;前面有 virtual 关键字的成员函数称为虚函数&#xff1b;virtual 关键字只用在类定义里的函数声明中&#xff0c;写函数体时不用。 class Base {virtual int Fun() ; // 虚函数 };int Base::Fun() // virtual 字段不用在函数体时定义 …

python- os模块

一、文件与目录相关的操作 1、删除文件/文件夹 2、os.stat("path/filename"): 获取文件/目录信息的结构说明 3、os.listdir 和 os.path.join 在Python中&#xff0c;os.listdir()和os.path.join()是操作系统模块&#xff08;os模块&#xff09;的两个函数&#x…

运维相关(一) - Vue项目配置WebSocket连接{ws、wss 连接方式}

Vue项目配置WebSocket连接 ws、wss 两种方式 1. 写作背景2. 晒出代码2.1 前端 vue.config.js 的代码2.2 Vue项目路由配置代码3.3 服务器Nginx配置 3. 使用方式3.1 前端代码3.2 后端代码 4. 测试使用 1. 写作背景 项目使用的是ruoyi的前后端分离框架项目需要使用到 websocket , …

上市公司-赫芬达尔指数(2000-2022年)(数据+2种结果)

上市公司-赫芬达尔指数&#xff08;HHI&#xff09;可衡量一个公司在市场中的相对份额或集中度。它是由每家公司在市场中份额的平方和得到的。指数值越高&#xff0c;表示该市场或行业的集中度越高&#xff0c;竞争可能相对较小&#xff1b;而指数值越低&#xff0c;则意味着该…

如何让群晖Audio Station公开共享的本地音频公网可访问?

文章目录 1. 本教程使用环境&#xff1a;2. 制作音频分享链接3. 制作永久固定音频分享链接&#xff1a; 之前文章我详细介绍了如何在公网环境下使用pc和移动端访问群晖Audio Station&#xff1a; 公网访问群晖audiostation听歌 - cpolar 极点云 群晖套件不仅能读写本地文件&a…

公众号开发实践:用PHP实现通过接口自定义微信公众号菜单

&#x1f3c6;作者简介&#xff0c;黑夜开发者&#xff0c;CSDN领军人物&#xff0c;全栈领域优质创作者✌&#xff0c;CSDN博客专家&#xff0c;阿里云社区专家博主&#xff0c;2023年6月CSDN上海赛道top4。 &#x1f3c6;数年电商行业从业经验&#xff0c;历任核心研发工程师…

Apache DolphinScheduler如何完全设置东八区?

默认情况 为了兼容全世界不同时区&#xff0c;Apache DolphinScheduler 使用的是 UTC 0 时区&#xff0c;包括保存到数据库表中的数据时区&#xff0c;以及展示到页面上的时区。 如果我们想在页面上看到东八区时间&#xff0c;则需要在页面上手动选择上海时区&#xff0c;如下…

小程序订单中心path设置本次审核不通过,审核原因:小程序尚未发布,无法审核。

小程序尚未发布&#xff0c;无法审核。 先按照这篇文章把小程序审核通过&#xff0c;小程序版本审核未通过&#xff0c;需在开发者后台「版本管理—提交审核——小程序订单中心path」设置订单中心页path&#xff0c;请设置后再提交代码审核 小程序审核通过后&#xff0c;发布…

2023.11.09 homework

4年级数学&#xff1a;不会做就作图&#xff0c;画出来&#xff0c;简单化就容易懂 2023.11.09 homework &#xff08;2&#xff09;-CSDN博客

MySQL代码子查询续集

dept表&#xff1a; emp表&#xff1a; -- 查询每个部门的信息(包括&#xff1a;部门名&#xff0c;编号&#xff0c;地址)和人员数量 -- 1.将两张表结合起来&#xff0c;筛选出部门名&#xff0c;编号&#xff0c;地址 tips: 表.* 表示将该表所有列都显示出来&#xff…

基于SpringBoot+Vue的婚恋相亲交友系统

基于SpringBootVue的婚恋相亲交友系统~ 开发语言&#xff1a;Java数据库&#xff1a;MySQL技术&#xff1a;SpringBootMyBatisVue工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 主页 管理员界面 摘要 基于SpringBootVue的婚恋相亲交友系统是一个现代化的、高效的交…

【算法设计】回溯法算法设计——骑士游历问题(C++实现)

创作不易&#xff0c;本篇文章如果帮助到了你&#xff0c;还请点赞 关注支持一下♡>&#x16966;<)!! 主页专栏有更多知识&#xff0c;如有疑问欢迎大家指正讨论&#xff0c;共同进步&#xff01; 更多算法分析与设计知识专栏&#xff1a;算法分析&#x1f525; 给大家跳…

【19】c++11新特性 —>线程异步

什么是异步&#xff1f; async的两种方式 //方式1 async( Function&& f, Args&&... args ); //方式2 async( std::launch policy, Function&& f, Args&&... args );函数参数&#xff1a; f:任务函数 Args:传递给f的参数 policy:可调用对象f的…