Netty implementing HTTP API Capabilities

Source: Internet
Author: User
Tags session id

No doubt, Netty is a Java network communication framework that supports high concurrency. This document scans the ability to use Netty to complete simple HTTP, without involving content such as security, business filtering, and so on.

Episode 1

/** * Start HTTP Server * @throws interruptedexception */private void Runhttpserver (Final eventproducer evtproducer) throws Interr uptedexception {//configure TCP server. Eventloopgroup bossgroup = new Nioeventloopgroup (serverbootoption.parent_eventloopgroup_ Threadnum); Eventloopgroup Workergroup = new Nioeventloopgroup (serverbootoption.child_eventloopgroup_threadnum); try { Serverbootstrap B = new Serverbootstrap (); B.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Option (Channeloption.so_backlog, 10240). Option (Channeloption.tcp_nodelay, True). Option (channeloption.connect_ Timeout_millis, 10000). Option (Channeloption.so_reuseaddr, True). Option (Channeloption.so_keepalive, True). Option ( Channeloption.so_linger, 0)//.childoption (channeloption.so_timeout, serverbootoption.so_timeout)//. Handler (New Logginghandler (Loglevel.info)). Childhandler (New channelinitializer<socketchannel> () {@Override protected void Initchannel (Socketchannel ch) throws Exception {Channelpipeline p = ch.pipeline (); P.addlast ("Idlestatehandler", New Idlestatehandler (), <span style= "color: #FF0000;" &GT;//Read Channel idle 60s, letter road idle 60s, read, Letter Road idle 30s</span> p.addlast ("Http_server_codec", New Httpservercodec ());//<span style= "COLOR: #FF0000;" >http Message Conversion </span> p.addlast ("Http_server_handler", New Httpproxyserverhandler (Manager,evtproducer));// <span style= "color: #FF0000;" > Message Processor </span>}}); Start the TCP server. Channelfuture f = b.bind (new inetsocketaddress (IP, port)). sync ();//<span style= "color: #FF0000;" > Start HTTP Service process </span>logger.info ("Start HTTP server ok");//Wait until the server socket is Closed.f.channel (). Closefuture (). sync ();} finally {//Shut ' All ' event loops to terminate all Threads.logger.info ("Shut ' all ' event loops to terminate all THR                         EADS. "); Bossgroup.shutdowngracefully ();//Close service process workergroup.shutdowngracefully ();//Close service Process}}
Clip 2HttpProxyServerHandler

/** * * @author * HTTP Request event handler, responsible for distributing HTTP request Events */public class Httpproxyserverhandler extends Channelhandleradapter{private Static final Logger Logger = Logger.getlogger (httpproxyserverhandler.class);p rivate Sessioncontextmanager Manager; <span style= "color: #FF0000;" >//Session Management </span>private final attributekey<long> timestamp = attributekey.valueof ("timestamp");p rivate Final StringBuilder buf = new StringBuilder ();p ublic Httpproxyserverhandler (Sessioncontextmanager manager) { This.manager=manager;} @Override public void handleradded (final Channelhandlercontext ctx) throws exception{logger.info ("[" +ct    X.channel (). ID (). Aslongtext () + "] is Added"); } @Override <span style= "color: #FF0000;" > Session off, fail event </span>public void Channelinactive (Channelhandlercontext ctx) throws Exception { Manager.getsession (). Remove (Ctx.channel (). ID (). aslongtext ()); Super.channelinactive (CTX);} @Override <span style= "color: #FF0000;" > Read message </span><span style= "color:#FF0000; "    > event, Business process entry </span> public void Channelread (final channelhandlercontext ctx, Object msg) throws Exception {    Logger.info ("Httpproxyserverhandler[channelread]");    attribute<long> Attr_timestamp = Ctx.channel (). attr (timestamp); Attr_timestamp.set (System.currenttimemillis ());//<span style= "color: #FF0000;" > Save status message in test channel </span>,<span style= "color: #FF0000;"    > such as the opening of the message processing time </span> sessioncontext sctx=new sessioncontext ();    Sctx.setctx (CTX);    Sctx.setchannelid (Ctx.channel (). ID ());    Sctx.setsessionactivetime ("" +system.currenttimemillis ()); Manager.getsession (). Put (Sctx.getchannelid (). Aslongtext (), sctx);//<span style= "color: #FF0000;" >manager.getsession () is a concurrent map structure for session hold </span> Logger.info (Sctx.getchannelid (). Aslongtext () + "req Time" +    System.currenttimemillis ());        try {dispatchmeesage (Ctx,manager, msg);        } finally {referencecountutil.release (msg); }}private Querystringdecoder QdecodeR = null;private string uri= "";//http uriprivate string Url= "";//http urlprivate map<string,list<string>> HT Tpreqparams=null;//http Request Parameter/** * Message distribution * @param CTX * @param manager * @param MSG message * @return * @throws Exception */privat E String dispatchmeesage (final channelhandlercontext ctx,final Sessioncontextmanager Manager, Final Object msg) throws Ex Ception{string decode_message = ""; Httpresponseutils util = new Httpresponseutils (); String result_code= "1", if (msg instanceof HttpRequest) {//HTTP request header HttpRequest req = (httprequest) Msg;url = Req.geturi (); I            F (url.equals ("/favicon.ico")) {ctx.close (); return "0";} if (!url.equals ("/billing")) {ctx.close (); return "0";}       if (is100continueexpected (req)) {//Ctx.write (New Defaultfullhttpresponse (Http_1_1, CONTINUE)); }qdecoder = new Querystringdecoder (URL); httpreqparams = Qdecoder.parameters (); URI = Qdecoder.path ();/* TODO: Identity authentication * IF ( Qdecoder.parameters (). ContainsKey ("crendial")) {* Crendial= (string *) qdecoder.parameters (). Get ("crendial"). Get (0). toUpperCase (); } */} else if (msg instanceof httpcontent) {///HTTP request body Httpcontent httpcontent = (httpcontent) msg; Bytebuf content = Httpcontent.content (); if (Content.isreadable ()) {String chunk_message=content.tostring (                 CHARSETUTIL.UTF_8);       Buf.append (chunk_message);} if (! ( msg instanceof lasthttpcontent) {//<span style= "color: #FF0000;"              > is not the last chunk packet, this key is very important, when the HTTP sub-chip transmission, you need to merge multiple pieces of content </span> return "0";             }else{decode_message= buf.tostring ();//Logger.info (decode_message); } if (msg instanceof lasthttpcontent) {//lasthttpcontent trailer = (lasthttpcontent) msg; String Sessionid=ctx.channel (). ID (). aslongtext (); SYSTEM.OUT.PRINTLN ("request" +decode_message); SYSTEM.OUT.PRINTLN ("Request Parameters" +httpreqparams); SYSTEM.OUT.PRINTLN ("Request Address" +uri); SYSTEM.OUT.PRINTLN ("session ID" +sessionid);//<span style= "color: #FF0000;" >todo: The simulation sends the request message to the backend processing, which can be put into the message queue, the CTX object enters the session hold (Map object), and so on after processing in the message queue is completed, the session is resumed and completedMessage reply. </span>}}return Result_code;}  private static Atomicinteger counter = new Atomicinteger (0), @Override public void Exceptioncaught (Channelhandlercontext        CTX, Throwable cause) throws Exception {manager.getsession (). Remove (Ctx.channel (). ID (). aslongtext ());        Cause.printstacktrace ();            Ctx.close (); } @Override public void usereventtriggered (Channelhandlercontext ctx, Object evt) throws Exception {Logger.error ("Ht        Tpproxyserverhandler[usereventtriggered] ");            if (evt instanceof idlestateevent) {idlestateevent e = (idlestateevent) evt;            if (e.state () = = Idlestate.all_idle) {logger.error ("All_idle");                } else if (e.state () = = Idlestate.reader_idle) {logger.error ("Reader_idle");            }else if (e.state () = = Idlestate.writer_idle) {logger.error ("Writer_idle");        } ctx.close (); }else if (evt instanceof errorevent) {logger.error ((errorevent) EVT). GetErrorCode ());        Ctx.close (); }            }}

Sessioncontext

Import Io.netty.channel.channelhandlercontext;import io.netty.channel.channelid;/** * HTTP request session * @author Wanghao * */ public class Sessioncontext {private Channelid channelid =null;/** session channel Id*/private Channelhandlercontext ctx;/** session */private string sessionactivetime;/** Session creation time */private string sessionunactivetime;/** session invalidation time */public string Getsessionactivetime () {return sessionactivetime;} public void Setsessionactivetime (String sessionactivetime) {this.sessionactivetime = Sessionactivetime;} Public String Getsessionunactivetime () {return sessionunactivetime;} public void Setsessionunactivetime (String sessionunactivetime) {this.sessionunactivetime = Sessionunactivetime;} Public Channelhandlercontext Getctx () {return CTX;} public void Setctx (Channelhandlercontext ctx) {this.ctx = CTX;} Public Channelid Getchannelid () {return channelid;} public void Setchannelid (Channelid channelid) {this.channelid = Channelid;}}

HTTP request Session Manager

Import java.util.map;/** * HTTP request Session Manager * @author  * */public interface Sessioncontextmanager {abstract map<string, Sessioncontext> getsession ();}



Netty implementing HTTP API Capabilities

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.