在 Netty 3 中,我们在每一端使用 LITTLE_ENDIAN ChannelBuffers
bootstrap.setOption("child.bufferFactory", new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN));
但在 Netty 4 中,ByteBuf 的配置现在似乎是通过 ChannelOption.ALLOCATOR:
bootstrap.option(ChannelOption.ALLOCATOR, someAllocator);
我们真正想做的就是装饰UnpooledByteBufAllocator,但它是final的,我们需要装饰的方法是受保护的,所以我们不能扩展类或委托给它。我们不得不求助于代理方法:
private static class AllocatorProxyHandler implements InvocationHandler {
private final ByteBufAllocator allocator;
public AllocatorProxyHandler(ByteBufAllocator allocator) {
this.allocator = allocator;
}
public static ByteBufAllocator proxy(ByteBufAllocator allocator) {
return (ByteBufAllocator) Proxy.newProxyInstance(AllocatorProxyHandler.class.getClassLoader(), new Class[]{ByteBufAllocator.class}, new AllocatorProxyHandler(allocator));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(allocator, args);
if (result instanceof ByteBuf) {
return ((ByteBuf) result).order(ByteOrder.LITTLE_ENDIAN);
} else {
return result;
}
}
}
像这样设置引导选项:
bootstrap.option(ChannelOption.ALLOCATOR, AllocatorProxyHandler.proxy(UnpooledByteBufAllocator.DEFAULT));
我们还缺少其他(更好的)方法吗?