基于netty的rpc架构

/ 2评 / 0

通过cmd可以进行通讯:

传统IO特点

NIO

Netty入门:

Netty工作原理源码分析

Netty3用线程池,netty5对线程池进行了封装

                                   protected void initChannel(Channel ch) throws Exception {

                                            ch.pipeline().addLast(new StringDecoder());设置编码

                                            ch.pipeline().addLast(new StringEncoder());设置解码

                                            ch.pipeline().addLast(new ServerHandler());设置处理

                                   }

                          });

心跳:

If(e instanceof IdleStateEvent){

If(((IdleStateEvent)e).getState() == IdleState.All_IDLE){

         //关闭链接

         Ctx.getChannel().close();

}

Else{

         Super.handleUpsteam(ctx,e);

}

}

序列化:

  1. protocol buff是一种协议,是谷歌推出的一种序列化协议

Protocolbuff:

Pause   方便观察错误

option java_outer_classname = "PlayerModule";

message PBPlayer{

         required int64 playerId = 1;

         required int32 age = 2;

         required string name = 3;

         repeated int32 skills = 4;

}

message PBResource{

         required int64 gold = 1;

         required int32 energy = 2;

}

playerModule.PBPlayer.paseFrom(bs);

arrayOutputStream.write();

byte[] byteArray=arrayOutputSteam.tobyteArray();

Byte[] idBytes=new byte[4];

arrayInputStream.read(idBytes);

ByteBuffer buffer = ByteBuffer.allocate(8);申请大小为8 的内存空间

Buffer.puInt(id)

Buffer.toarrray()

ByteBuffer buffer2 =Bytebuffer.warp(array);

Buffer2.getInt();

ChannelBuffer buffer=ChannelBuffers.dynamicBuffer();

Buffer.write()

Channel buffer wrappedBuffer = ChannelBuffers.wrappedBuffer(bytes);

wrappedBuffer.readInt();

=0111 1111

0111=7

1111=f

while(true){

if(buffer.readInt()==ConstantValue.FLAG){

         break;

}

}

消息如何在管道中流转:

handler往下传递对象的方法时sendUpsteam()

socket客户端:

         Socket socket=new socket(“127.0.0.1”,10101);

         socket.getOutputStream().write(“hello”.getBytes());

粘包分包处理:

Bytebuffer buffer =ByteBuffer.allocate(4+bytes.length);

buffer.putInt(bytes.length);

buffer.put(bytes);

byte[] array = buffer.array()

if(buffer.readableBytes()>4){

//标记

         buffer.markReaderIndex();

         //长度

int length= buffer.readInt();

if(bufer.readableBytes()<length{

         //还原

         buffer.restReaderIndex();              

         //缓存当前剩余buffer,等待下次数据到来

         return null

}

}

//读数据

byte[] bytes=new byte[length];

buffer.readBytes(bytes);

//向下传对象

return new String(bytes);

继承FrameDecoder特性:

长度+数据:

if(buffer.readableBytes(){

         buffer.skipbytes(buffer.readalbeBytes());   

}

添加包头标识,上面有例子

借助spring实现业务分离:

netty3 到 netty5

使用完释放,池的效率更高

或UnpooledByteBufAllocator

业务线程池 

2条回应:“基于netty的rpc架构”

  1. worthy说道:

    滴滴

发表评论

电子邮件地址不会被公开。 必填项已用*标注