使用Netty 的 ChannelOption 和屬性

2018-08-03 16:38 更新

如果每次創(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,常見類用于插入和檢索屬性值。屬性允許您安全的關(guān)聯(lián)任何數(shù)據(jù)項與客戶端和服務(wù)器的Channel。

例如,考慮一個服務(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();
  1. 新建一個 AttributeKey 用來存儲屬性值
  2. 新建 Bootstrap 用來創(chuàng)建客戶端管道并連接他們
  3. 指定 EventLoopGroups 從和接收到的管道來注冊并獲取 EventLoop
  4. 指定 Channel 類
  5. 設(shè)置處理器來處理管道的 I/O 和數(shù)據(jù)
  6. 檢索 AttributeKey 的屬性及其值
  7. 設(shè)置 ChannelOption 將會設(shè)置在管道在連接或者綁定
  8. 存儲 id 屬性
  9. 通過配置的 Bootstrap 來連接到遠程主機


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號