带有FileRegion的Netty 4 MessageToByte编码器

带有FileRegion的Netty 4 MessageToByte编码器,netty,Netty,我正在从原始NIO迁移到netty。我需要回复如下 short long long long file 我有下面的工作示例,我想知道如何将FileRegion移动到编码器中 MessageToByte编码器 @Override protected void encode(final ChannelHandlerContext ctx, final BlockResponse msg, final ByteBuf out) throws Exception { out.writeSh

我正在从原始NIO迁移到netty。我需要回复如下

short
long
long
long
file
我有下面的工作示例,我想知道如何将FileRegion移动到编码器中

MessageToByte编码器

@Override
protected void encode(final ChannelHandlerContext ctx, final BlockResponse msg,
    final ByteBuf out) throws Exception {
  out.writeShort(DataServerMessage.DATA_SERVER_RESPONSE_MESSAGE);
  out.writeLong(msg.getBlockId());
  out.writeLong(msg.getOffset());
  out.writeLong(msg.getLength());
}
沟道边界HandlerAdapter

    ctx.write(new BlockResponse(blockId, offset, readLength));
    FileChannel channel = closer.register(file.getChannel());
    ChannelFuture future = ctx.writeAndFlush(new DefaultFileRegion(channel, offset, readLength));
    future.addListener(ChannelFutureListener.CLOSE);
ChannelFuture future =
    ctx.writeAndFlush(new BlockResponse(blockId, offset, readLength, channel));
future.addListener(ChannelFutureListener.CLOSE);
future.addListener(new ClosableResourceChannelListener(file));
我认为,如果我在适配器中写入响应(并将文件放在那里),那么我可以在编码器中执行另一个writeAndFlush,但是编码器需要关闭它。还有别的办法吗

谢谢

编辑:

以下是有效的更新代码:

public static final class Encoder extends MessageToMessageEncoder<BlockResponse> {
  private static final int HEADER_LENGTH = 2 + 4 * 3; // short, 3 longs

  @Override
  protected void encode(final ChannelHandlerContext ctx, final BlockResponse msg,
      final List<Object> out) throws Exception {
    out.add(createHeader(ctx, msg));
    if (msg.getChannel() != null) {
      out.add(new DefaultFileRegion(msg.getChannel(), msg.getOffset(), msg.getLength()));
    }
  }

  private ByteBuf createHeader(final ChannelHandlerContext ctx, final BlockResponse msg) {
    ByteBuf header = ctx.alloc().buffer(HEADER_LENGTH);
    header.writeShort(DataServerMessage.DATA_SERVER_RESPONSE_MESSAGE);
    header.writeLong(msg.getBlockId());
    header.writeLong(msg.getOffset());
    header.writeLong(msg.getLength());
    return header;
  }
}

如果还需要从编码器内触发FileRegion,则需要使用MessageToMessageEncoder,并在其中按自己的方式分配ByteBuf

所以我分配我自己的头(从ctx)并将其作为out.add(头)发送,然后我说out.add(fileRegion)?我试试这个,谢谢!