W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
如果每次創(chuàng)建通道后都不得不手動配置每個通道,這樣會很麻煩,所幸,Netty提供了 ChannelOption 來幫助引導(dǎo)配置。這些選項都會自動的應(yīng)用到引導(dǎo)創(chuàng)建的所有通道中去,可用的各種選項可以配置底層連接的詳細信息,如通道“keep-alive(保持活躍)”或“timeout(超時)”的特性。
Netty 應(yīng)用程序通常會與組織或公司其他的軟件進行集成,在某些情況下,Netty 的組件如 Channel 會在 Netty 正常生命周期外使用;Netty 的提供了抽象 AttributeMap 集合,這是由 Netty的管道和引導(dǎo)類,和AttributeKey
例如,考慮一個服務(wù)器應(yīng)用程序跟蹤用戶和Channel之間的關(guān)系。這可以通過存儲用戶ID作為Channel的一個屬性。類似的技術(shù)可以用來路由消息到基于用戶ID或關(guān)閉基于用戶活動的一個管道。
清單9.7展示了如何使用 ChannelOption 配置 Channel 和一個屬性來存儲一個整數(shù)值。
Listing 9.7 Using Attributes
final AttributeKey<Integer> id = new AttributeKey<Integer>("ID"); //1
Bootstrap bootstrap = new Bootstrap(); //2
bootstrap.group(new NioEventLoopGroup()) //3
.channel(NioSocketChannel.class) //4
.handler(new SimpleChannelInboundHandler<ByteBuf>() { //5
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
Integer idValue = ctx.channel().attr(id).get(); //6
// do something with the idValue
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
System.out.println("Reveived data");
}
});
bootstrap.option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); //7
bootstrap.attr(id, 123456); //8
ChannelFuture future = bootstrap.connect(new InetSocketAddress("www.manning.com", 80)); //9
future.syncUninterruptibly();
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: