Spring Boot Web +WebSocket(Netty) Protocol Buffer项目框架

大概历时2个月,并发量超过10k的web+websocket框架配置 (并发量可以更高,没有超过10k哈)

1.Spring Boot Web
基于Spring Boot 内嵌的Tomcat开发

2.Netty (Websocket)
基于Netty开发 集合心跳机制 Google 的Protocol Buffer传输(减少传输体积)

3.Log4j2
采用Log4j2日志框架

4.ProtocolController ProtocolService
自己写了个简单的AOP框架 方便使用WebSocket开发

如果有兴趣的可以私信我,这篇文章还在编写中。后期会放出github代码

解答博友问题

1.Netty如何主动向client发送消息

首先你要确定你有如下信息:
①client已经和服务器建立socket连接
②在handlerAdded方法中你获取到了client的channel在这里插入图片描述
③.在ChannelInitializer中已经添加你的编解码器
在这里插入图片描述

④.发送消息到client
在这里插入图片描述
⑤核心是调用 client的 channel.writeAndFlush方法

自己在用的Protobuf编解码器

Protobuf编解码器代码如下
编码器

import cn.boommanpro.common.ProtoBufUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class ProtoBufDecoder extends ByteToMessageDecoder {
    private Class<?> genericClass;

    public ProtoBufDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    public final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }

        in.markReaderIndex();
        int dataLength = in.readInt();
        if (dataLength < 0) {
            log.error("dataLength长度出错:{},ctxRemoteAddress信息:{}",dataLength,ctx.channel().remoteAddress());
            ctx.close();
        }
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        Object obj = ProtoBufUtil.deserializer(data, genericClass);
        out.add(obj);


    }
}

解码器

import cn.boommanpro.common.ProtoBufUtil;
import cn.boommanpro.server.socket.module.rtp.model.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author BoomMan
 */
public class ProtoBufEncoder extends MessageToByteEncoder<Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        byte[] serializer = ProtoBufUtil.serializer(msg);
        out.writeInt(serializer.length);
        out.writeBytes(serializer);
    }
}

用到的工具类也是自己改良过的,详细见文章

Protocol Buffer(Protobuf) For Java

关于Netty的文章,不断在更新哦:一篇文章彻底学会Netty

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值