大概历时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