简体   繁体   中英

Singleton bootstrap and pipelineFactory on Netty as Tcp Client

I'm using Netty to implement a server and a client of a protocol over TCP. At the server side, I created one instance of classes bootStrap and pipelineFactory for each port it listen to, and it works great and quickly.

However at the client side I haven't got a clear idea about how to structure it. I need to open thousand connections to thousands differents destinations. I'm developing the project on Spring Framework so I can easily create singleton bean and inject them as properties. I'm evaluating 3 options:

  • Use a singleton instance of ClientBootstrap and PipelineFactory. Every connection uses some code like this to get a channel:

     public Channel connect(final InetSocketAddress serverAddress, final ChannelPipelineFactory pipelineFactory, int timeout, TimeUnit unit) throws InterruptedException { ChannelFuture future; synchronized (bootstrap){ bootstrap.setPipelineFactory(pipelineFactory); future = bootstrap.connect(serverAddress); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { //TODO set here some channelLocal properties I need to configure the session (eg: user, password etc...) } else{ throw new RuntimeException(future.getCause() .getMessage()); } } }); } return future.getChannel(); 

    }

My solution have to be able to configure also the pipeline to enable or disable SSL or log handlers, maybe using this Abe solution to configure getPipeline()

  • My second option is to use a singleton instance of ClientBootstrap but create a new PipelineFactory on every outgoing client connection. This helps me to configure the pipeline I have, because I can set properties on the pipelineFactory instance.

  • Third option is to create new bootStrap objects and pipelineFactory on every outgoing connection. This allows me to configure properties like tcp.delay or tcp.keepalive on every connection and allow me to delete the synchronized block on connect method, that could speed up client connections.

I think first one is fastest and use the lowest memory, but third one is the most configurable and maybe easy to develop.

Could you give me some advices about pros and cons of this approaches? maybe one of them is wrong?

Thank you very much!

ClientBootstrap instances are cheap. I would just create a new one for every connect and reuse the NioSocketClientChannelFactory for all of them. Or if you can you may want to use one bootstrap for ssl connections and one for non ssl. This will safe you from some memory overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM