java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Netty Constant类

一文详解Java Netty中的Constant类

作者:KittyGuy

这篇文章主要介绍了Constants类即常量类是将一些常用的变量集合到一个地方的类,文中有详细的代码示例,感兴趣的同学可以参考一下

Constant

class Main {
   public static void main(String[] args) {
      MyConstant value = new MyConstant();
      System.out.println(value.PI);
      System.out.println(value.object);
  }
  static class MyConstant implements Constant<MyConstant> {
      public double PI = 3.1415926;
      public Object object = new Object();
      private final int id;
      private final String name;
      public MyConstant() {
          id = new Random().nextInt();
          name = id + "#";
      }
      @Override
      public int id() {
          return id;
      }
      @Override
      public String name() {
          return name;
      }
      @Override
      public int compareTo(MyConstant other) {
          return Integer.compare(id, other.id);
      }
   }
}

ChannelConfig

Channel ch = ...; 
SocketChannelConfig cfg = (SocketChannelConfig) ch.getConfig(); 
cfg.setTcpNoDelay(false);

Option map是一个动态的只写属性,允许在不向下转换其关联的ChannelConfig的情况下配置一个Channel。

Channel ch = ...; 
Map<ChannelOption<?>, Object> options = new HashMap<>(); 
options.put(ChannelOption.SO_TIMEOUT, 5000); 
options.put(ChannelOption.SO_KEEPALIVE, true); 
ch.config().setOptions(options);
//不需要SocketChannelConfig cfg = (SocketChannelConfig) ch.getConfig();
//所有Channel都可以用
名称 关联的设置方法 
ChannelOption.CONNECT_TIMEOUT_MILLIS setConnectTimeoutMillis(int)
ChannelOption.WRITE_SPIN_COUNT setWriteSpinCount(int) 
ChannelOption.WRITE_BUFFER_WATER_MARK setWriteBufferWaterMark(WriteBufferWaterMark)
ChannelOption.ALLOCATOR setAllocator(ByteBufAllocator) 
ChannelOption.AUTO_READ setAutoRead(boolean)

Netty中重要的Constant实现类:ChannelOption和AttributeKey

ChannelOption

Bootstrap b = new Bootstrap(); 
b.group(group) 
 .channel(NioSocketChannel.class) 
 .remoteAddress(new InetSocketAddress("example.com", 80)) 
 // 使用 ChannelOption 配置连接超时时间 
 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)

AttributeKey

public class MyHandler {
 private final Attribute<AtomicInteger> messageCounterAttr;

 public MyHandler(Channel channel) {
     messageCounterAttr = channel.attr(AttributeKey.valueOf("messageCounter"));
     messageCounterAttr.set(new AtomicInteger(0));
 }

 public void handle(Object msg) {
     // increment message counter
     AtomicInteger messageCounter = messageCounterAttr.get();
     messageCounter.incrementAndGet();

     // do other things with the message
     // ...
 }
}

源码学习

小结

以上就是一文详解Java Netty中的Constant类的详细内容,更多关于Netty Constant类的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文