Netty + Protobuf 的客户端模式运用和问题探讨

使用NETTY之前,当然需要先看一下所带的samples。

 

简单的hello world,可能大家都没啥感觉,觉得NETTY其实很简单:

 

1. 对于服务器端,需要写下面几个:

a. 写个ServerHandler,来接收并处理服务端业务逻辑;

b. 照葫芦画瓢整个Pineline,比如ServerPipelineFactory,把一些现成的和自己的ServerHandler串糖葫芦那样串起来;

c. 最后写个简单的Server,把ServerBootstrap和ServerPipelineFactory装起来;

d. 好吧,再加一些优化/适合的参数,比如child.tcpNoDelay,child.keepAlive之类的。

典型代码如下:

ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                		Executors.newCachedThreadPool(),
                		Executors.newCachedThreadPool(),
                		threadpool_worker)
                );

        // Parameters for tuning
        bootstrap.setOption("child.tcpNoDelay", true);
        //bootstrap.setOption("child.keepAlive", true);
        
        // Set up the event pipeline factory.
        bootstrap.setPipelineFactory(serverPipelineFactory);

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(port));
        
        // please use System.out directly here. DON'T CHANGE IT!!!
        System.out.println("====Server is ready to rock on port:" + port + "====");
 

 

2. 对于客户端,其实与服务器端非常相似,如下:

a. 写个ClientHandler,来接收并处理客户端业务逻辑;

b. 照葫芦画瓢整个Pineline,比如ClientPipelineFactory,把一些现成的和自己的ClientHandler串糖葫芦那样串起来;

c. 最后写个简单的Client,把ClientBootstrap和ClientPipelineFactory装起来。

典型代码如下:

// Set up.
        bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Configure the event pipeline factory.
        bootstrap.setPipelineFactory(new ClientPipelineFactory());

        // Make a new connection.
        logger.debug("trying to connect to host[{}] and port[{}]...", host, port);
        channelFuture = bootstrap.connect(new InetSocketAddress(host, port));

        // Wait until the connection is made successfully.
        channel = channelFuture.awaitUninterruptibly().getChannel();
        logger.debug("successfully connected to host[{}] and port[{}]!", host, port);
 

一般而言,hello world就可以玩了。

 

 

但对于实战性的应用开发,问题才刚刚开始:

1. 针对NETTY,合理的设计模式如何运用?

对于服务端,往往是在ServerHandler里,接收=》处理=》write,一般关照好messageReceived方法即可,比较简单,至于如何搞定你的业务逻辑设计,跟NETTY无关,在此不谈。

对于客户端,我们不得不关心,有几个要点:

a. 收发是异步的,如果发送者只管发而不管后果,这也可以不谈,跟Server端一样,非常简单

b. 如果发送者发了还要管收,这就来劲了,怎么玩?这是我们要探讨的第一个问题,我先抛出来,接下来再议

 

2. 为了引入高性能的binary protocol, 引入了google的protobuf,暂时没发现问题,如果是同构平台(java)的话,堪称完美,但由于netty针对protocol有专门的Decoder/Encoder。

问题二是:我google了半天,好像没有教好的案例,可以实现异构平台(如.net)访问NETTY + Protobuf的参考?

 

 

各位如有经验的,可以来分享、讨论,我会继续跟进。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章