Netty:使用池化缓冲区进行写入

时间:2014-06-24 15:07:52

标签: java netty

我目前正在使用Netty进行POC工作,直到目前为止它非常好并且设法启动并运行了一些功能。

然而,我有一个问题是重用字节缓冲区进行写入。在下面的示例中,您可以看到手动创建的bytebuffer-response,但它是为每个请求创建的,并且不需要。我想使用' buf'。我目前正在试用和错误模式下运行,我已经查看了这些示例。虽然我的案例看起来非常标准,但我还是无法找出制作池化缓冲区的正确方法。

  public class OperationHandler extends ChannelInboundHandlerAdapter {
    private ByteBuf buf;

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        buf = ctx.alloc().buffer(1024);
        //    System.out.println("Channel handler added");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        buf.release();
        buf = null;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            ByteBuffer response = ByteBuffer.allocate(1024);
            byte[] operation = (byte[]) msg;
            invoker.invoke(operation, response);
            response.flip();
            ctx.write(Unpooled.wrappedBuffer(response));
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}

0 个答案:

没有答案