1

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 をデコレートすることだけですが、これは最終的なものであり、デコレートする必要のあるメソッドは保護されているため、クラスを拡張したりデリゲートしたりすることはできません。プロキシ アプローチに頼る必要がありました。

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 オプションを次のように設定します。

    bootstrap.option(ChannelOption.ALLOCATOR, AllocatorProxyHandler.proxy(UnpooledByteBufAllocator.DEFAULT));

これを行うための他の(より良い)方法はありますか?

4

1 に答える 1