As we all know, Netty is a high-performance I/O framework, how to build Web services on it, today, online search an article, learning a bit:
Java Servlets has been vastly used in companies for more than all years now. Recently another project from JBoss named Netty have gained on popularity to serve data. From Netty website: "Netty have succeeded to find a-to achieve ease of development, performance, stability, andfle Xibility without a compromise.".
But on the moment to serve data or to handle requests, you need to choose for the implementation either for a Servlet or F or Netty.
As main developer of Xins, an Open-source Web services framework, I ' ve developed a few years ago a basic Servlet container To is able to run unit tests and to run WAR if you wanted to with Java-jar My-api.war or xins run-my-api.
For the release of Xins 3.0, I ' ve decided-put the Servlet container on top of Netty.
Netty takes cares of the IO and the HTTP handling and my Servlet container takes care of the handling of the HTTP request To the Servlet itself.
How to do it
First you need to handle HTTP data with a Netty channelpipeline using a pipeline factory:
public class Defaultnettyservletpipelinefactory implements Channelpipelinefactory {... public channelpipeline Getpipeline () throws Exception { Channelpipeline pipeline = Pipeline (); Pipeline.addlast ("Decoder", New Httprequestdecoder ()); Pipeline.addlast ("encoder", New Httpresponseencoder ()); Pipeline.addlast ("Deflater", New Httpcontentcompressor ()); Pipeline.addlast ("handler", Servlethandler); Would convert HTTP request to servlet request return pipeline;}
Then you'll need a nettyservlethandler that converts Netty HttpRequest to a Servlet request:
public class Nettyservlethandler extends Simplechannelupstreamhandler {... @Overridepublic void messagereceived ( Channelhandlercontext context, Messageevent event) throws Exception { HttpRequest request = (HttpRequest) Event.getmessage (); Then get URL, method, headers, ... and pass the values to the Servlet container.}
You'll also need a method to start the server:
public void StartServer (int port, String pipelinefactory) throws Exception { serverbootstrap server = new SERVERBOOTST Rap ( New Nioserversocketchannelfactory (Executors.newcachedthreadpool (), Executors.newcachedthreadpool ())); if (pipelinefactory = = null) {//If the user doesn ' t has a specific pipeline use the default one pipelinefactory = " Org.xins.common.servlet.container.DefaultNettyServletPipelineFactory "; } Defaultnettyservletpipelinefactory Pipelinefactoryclass = (defaultnettyservletpipelinefactory) Class.forName ( pipelinefactory). newinstance (); Pipelinefactoryclass.setservlethandler (this); Server.setpipelinefactory (pipelinefactoryclass); Server.bind (New Inetsocketaddress (port)); }
and voilà! Your Server code has the best of both Worlds:it uses a standard API and it runs on Netty.
Building a servlet on Netty