侧栏导航

优化性能的思路


优化性能的思路,随笔

GateWay转发性能优化

空间换时间

为每个client端分配一个Context

  1. Client建立连接时为其分配一个Context,同时解包,解析转发目标
  2. 在Context中再划定一块内存来保存转发目标,
  3. 后续收到Client的消息时,直接转发到目标

这样就不用去拆包,避免拷贝内存,从而提升性能,缺点是占用内存

对于来自同一个连接的消息会转发到多个目标的情况.我们应该在设计上避免出现此类情况.原则是一个端口一个转发目标

避免不必要的内存拷贝

通常消息有Header和Body组成,Header和Body被分开创建

 +--------+----------+
 | header |   body   |
 +--------+----------+

常见的做法是新建一个更大的Buffer, 将Header和Boby分别拷贝到Buffer中

Buffer msgBuf = new Buffer();
msgBuf.write(HeaderBuf);
msgBuf.write(BodyBuf);

这样就产生了2次内存拷贝和一次内存创建

针对这种情况. 我们可以申明一个复合类型的MixingBuffer类,并且继承自Buffer

MixingBuffer内部持有Header和Boby对象. 重写read和wite方法, 实际读写还是操作Header和Body

MixingBuffer mixingBuf = MixingBuffer.wrappedBuffer(message, footer);

Buffer msgBuf = (Buffer)mixingBuf;

设计思路参考Netty的Buf包设计

 // The composite type is compatible with the component type.
 ByteBuf message = Unpooled.wrappedBuffer(header, body);

 // Therefore, you can even create a composite by mixing a composite and an
 // ordinary buffer.
 ByteBuf messageWithFooter = Unpooled.wrappedBuffer(message, footer);

 // Because the composite is still a ByteBuf, you can access its content
 // easily, and the accessor method will behave just like it's a single buffer
 // even if the region you want to access spans over multiple components.  The
 // unsigned integer being read here is located across body and footer.
 messageWithFooter.getUnsignedInt(
     messageWithFooter.readableBytes() - footer.readableBytes() - 1);

最后更新于 2nd Aug 2019
微信二维码
在微信上关注我