Transport Configuration (Transport 的 配置)
我们先从一个简单的创建开始:
-
final TCPNIOTransportBuilder builder = TCPNIOTransportBuilder . newInstance ();
-
final TCPNIOTransport transport = builder . build ();
这样就创建了一个Transport,如果我们想建立服务端,接下来就是绑定端口和开启服务:
-
final TCPNIOTransportBuilder builder = TCPNIOTransportBuilder . newInstance ();
-
final TCPNIOTransport transport = builder . build ();
-
try {
-
// Bind server socket and start transport
-
transport . bind ( 12345 );
-
transport . start ();
-
-
System . out . println ( "Press <enter> to exit..." );
-
System . in . read ();
-
} catch ( Exception e ){
-
e . printStackTrace ();
-
}
Systen.in.read()的作用还是不让Main线程结束,因为transport创建的Selector线程或者Worker都是虚拟线程(虚拟线程什么特点网上有资料)。
按如上所述就开启了端口为12345的一个服务端了。
如果我们需要创建客户端,那么可以通过transport建立到某个地址+端口的连接:
-
final TCPNIOTransportBuilder builder = TCPNIOTransportBuilder . newInstance ();
-
final TCPNIOTransport transport = builder . build ();
-
Future < Connection > fc = transport . connect ( "127.0.0.1" , 12345 );
-
Connection conn = fc . get ();
-
conn . write ( message );
其中message的格式根据自定义的Filter而变化,如果是底层的,message就是一个Buffer。
接下来还是主要看下我常用的配置:
IOStrategy |
这个之前有讲解基本有如下几个:
|
memoryManager | 这个就是内存管理器:有Heap和ByteBuffer两种。 |
processor |
这个一般设置FilterChain,我们可以在FilterChain里面添加自己的滤镜,用于处理消息
|
readBufferSize | 读数据流的分配内存大小 |
writeBuffersSize |
写数据流的内存分配大小,一般可以根据工程而配置。
|
Thread Pool Configuration
好了,基本使用已经学会,那么我们看看几个参数的作用:
-
final TCPNIOTransportBuilder builder = TCPNIOTransportBuilder . newInstance ();
-
final ThreadPoolConfig config = builder . getWorkerThreadPoolConfig ();
-
config . setCorePoolSize ( 5 ). setMaxPoolSize ( 5 ). setQueueLimit (- 1 );
-
final TCPNIOTransport transport = builder . build ();
queue | 任务队列 |
queueLimit | 队列最大容纳的数量 |
threadFactory | 线程工厂,用于创建Worker线程或其他线程。。。 |
poolName | 线程池的名称 |
priority | The priority to be assigned to each thread. This will override any priority assigned by the specified ThreadFactory. |
corePoolSize | 初始线程数 |
maxPoolSize | 最大线程数,-1表示无限大 |
keepAliveTime | The maximum time a thread may stay idle and wait for a new task to execute before it will be released. Custom time units can be used. |
transactionTimeout | The maximum time a thread may be allowed to run a single task before interrupt signal will be sent. Custom time units can be used. |