最近用了一段時間的Netty,現構建了一個編碼器/解碼器管道,以測試編碼器和解碼器在沒有發送真實的消息時是否在正常工作。
方便的是,Netty 有個 EmbeddedChannel,使測試變得非常輕鬆。
假設我們有一條消息“ Foo”,我們想通過網絡發送。它僅包含一個整數值,因此我們將其發送並在另一側重建“ Foo”。 我們可以編寫以下編碼器來執行此操作:
public static class MessageEncoder extends MessageToMessageEncoder<Foo> { @Override protected void encode( ChannelHandlerContext ctx, Foo msg, List<Object> out ) throws Exception { ByteBuf buf = ctx.alloc().buffer(); buf.writeInt( msg.value() ); out.add( buf ); } } public static class Foo { private Integer value; public Foo(Integer value) { this.value = value; } public int value() { return value; } }
因此,我們要做的就是從“ Foo”中拿到“ value”字段並將其放入列表,該列表會向下傳遞。
編寫一個測試,該測試模擬發送“ Foo”消息並使用空的解碼器嘗試處理該消息:
@Test public void shouldEncodeAndDecodeVoteRequest() { // given EmbeddedChannel channel = new EmbeddedChannel( new MessageEncoder(), new MessageDecoder() ); // when Foo foo = new Foo( 42 ); channel.writeOutbound( foo ); channel.writeInbound( channel.readOutbound() ); // then Foo returnedFoo = (Foo) channel.readInbound(); assertNotNull(returnedFoo); assertEquals( foo.value(), returnedFoo.value() ); } public static class MessageDecoder extends MessageToMessageDecoder<ByteBuf> { @Override protected void decode( ChannelHandlerContext ctx, ByteBuf msg, List<Object> out ) throws Exception { } }
在測試中,我們將“ Foo”寫入出站通道,然後將其讀回入站通道,然後檢查我們所獲得的內容。如果我們現在運行該測試,將會看到以下內容:
junit.framework.AssertionFailedError at NettyTest.shouldEncodeAndDecodeVoteRequest(NettyTest.java:28)
我們返回的消息爲空,這是有道理的,因爲我們沒有編寫解碼器。然後實現解碼器:
public static class MessageDecoder extends MessageToMessageDecoder<ByteBuf> { @Override protected void decode( ChannelHandlerContext ctx, ByteBuf msg, List<Object> out ) throws Exception { int value = msg.readInt(); out.add( new Foo(value) ); } }
現在,如果我們再次運行測試,那一切就變成綠色。現在,我們可以對一些更復雜的結構進行編碼/解碼,並相應地更新測試。
原文地址: https://www.zhblog.net/go/java/tutorial/java-netty-encoder-decoder?t=603