使用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的參考?
各位如有經驗的,可以來分享、討論,我會繼續跟進。