Netty's restful API simple implementation and deployment

Source: Internet
Author: User
Tags vps scp command vps server
1 BEGIN

Netty is a NIO based customer, server-side programming framework that uses Netty to ensure that you quickly and easily develop a network application, such as a client that implements a certain protocol, a service-side application. Netty fairly simplifies and streamlines the programming of network applications, such as the development of socket services for TCP and UDP.

Netty is an asynchronous server-side network programming framework that uses Netty to quickly develop the services that are needed. At present, many companies use Netty to develop game servers. The efficiency of Netty attracts the attention of many developers.

Since Netty is not a dedicated Web/restful server framework, all Netty development RESTful services need to add some additional modules themselves. Here is a simple implementation of the RESTful service, used to calculate the body mass index and basal metabolic rate (basal metabolic Rate, referred to as BMR), and deployed to the VPS.

BMI index (Body mass index, or BMI) is also called Body Mass Index, which is Mass index in English.

Basal Metabolic rate (basal metabolic Rate, referred to as BMR) is the lowest calorie we consume in a quiet state (usually in a quiescent state), and the rest of the human activity is based on this. 2 start Serverbootstrap (establish connection)

Download the Netty Jar http://netty.io/to the official website of Netty, where the Netty version is 4.1.6. Download the compression package after decompression, under the/jar/all-in-one have Nettyall-4.1.6.final.jar file, this is Netty compiled out of the jar.

Use Eclipse to create a new project, create a new Lib folder in the project, put the above jar in a folder, and add the jar to the project through build path. This project uses Orgjson as the parsing library for JSON, and the same Org-json-20160810.jar is added to the project (Org-json-jar download address).

Create a new Java class Mainserver and join the Serverbootstrap startup code. This part of the code originates from the Netty http Example, and all Netty service startup code is similar to this.

Package com.health;
Import Io.netty.bootstrap.ServerBootstrap;
Import Io.netty.channel.Channel;
Import io.netty.channel.ChannelOption;
Import Io.netty.channel.EventLoopGroup;
Import Io.netty.channel.nio.NioEventLoopGroup;
Import Io.netty.channel.socket.nio.NioServerSocketChannel;
Import Io.netty.handler.logging.LogLevel;
Import Io.netty.handler.logging.LoggingHandler;
Import Io.netty.handler.ssl.SslContext;
Import Io.netty.handler.ssl.SslContextBuilder;


Import Io.netty.handler.ssl.util.SelfSignedCertificate; /** * Service Main entrance * @author Superzhan * * */Public final class Mainserver {/* Whether to use HTTPS protocol/static final Boolean SS
    L = System.getproperty ("SSL")!= null; static final int PORT = Integer.parseint (System.getproperty ("Port", SSL?)

    "8443": "6789"));
        public static void Main (string[] args) throws Exception {//Configure SSL.
        Final Sslcontext Sslctx;
            if (SSL) {selfsignedcertificate SSC = new Selfsignedcertificate (); Sslctx = Sslcontextbuilder.forserver (Ssc.certificate (), Ssc.privatekey ()). build ();
        else {sslctx = null;
        }//Configure the server.
        Eventloopgroup Bossgroup = new Nioeventloopgroup (1);
        Eventloopgroup Workergroup = new Nioeventloopgroup ();
            try {serverbootstrap b = new Serverbootstrap ();
            B.option (Channeloption.so_backlog, 1024); B.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Handler (New Logginghandl

            ER (loglevel.info)). Childhandler (New Serverinitializer (SSLCTX));

            Channel ch = b.bind (PORT). Sync (). Channel (); System.err.println ("Open your Web browser and navigate to" + (SSL?)

            HTTPS ":" http ") +"://127.0.0.1: "+ PORT + '/");
        Ch.closefuture (). sync ();
            finally {bossgroup.shutdowngracefully ();
        Workergroup.shutdowngracefully ();
}
    }
} 
3 Channelinitializer (initial connection)

Create a new class Serverinitializer in the project that is used for the initialization of the connection.

Package com.health;

Import Io.netty.channel.ChannelInitializer;
Import Io.netty.channel.ChannelPipeline;
Import Io.netty.channel.socket.SocketChannel;
Import Io.netty.handler.codec.http.HttpObjectAggregator;
Import Io.netty.handler.codec.http.HttpServerCodec;
Import Io.netty.handler.ssl.SslContext;

public class Serverinitializer extends channelinitializer<socketchannel> {

    private final sslcontext sslctx;< C8/>public Serverinitializer (Sslcontext sslctx) {
        this.sslctx = sslctx;
    }

    @Override public
    void Initchannel (Socketchannel ch) {
        Channelpipeline p = ch.pipeline ();
        if (sslctx!= null) {
            p.addlast (Sslctx.newhandler (Ch.alloc ()));
        P.addlast (New Httpservercodec ()), decoder for/*http service/
        p.addlast (New Httpobjectaggregator (2048)), merge of/*HTTP messages * *
        P.addlast (New Healthserverhandler ())//* Write the Server logic processing/
    }

4 Channelhandler (Business Controller)

The above two code is a fixed function of the framework code, the business controller handler is the part of its own play. Need to get the request URI of the client to do the routing distribution, different requests do different response. The client's request data is parsed into a JSON object for easy operation. Generate a JSON data from the calculated result to send back to the client.

Package com.health;
Import Io.netty.buffer.ByteBuf;
Import io.netty.buffer.Unpooled;
Import Io.netty.channel.ChannelFutureListener;
Import Io.netty.channel.ChannelHandlerContext;
Import Io.netty.channel.ChannelInboundHandlerAdapter;
Import Io.netty.handler.codec.http.DefaultFullHttpResponse;
Import Io.netty.handler.codec.http.FullHttpRequest;
Import Io.netty.handler.codec.http.FullHttpResponse;
Import Io.netty.handler.codec.http.HttpMethod;
Import Io.netty.handler.codec.http.HttpUtil;
Import io.netty.util.AsciiString;

Import Io.netty.util.CharsetUtil;
Import static io.netty.handler.codec.http.httpresponsestatus.*;



Import static io.netty.handler.codec.http.httpversion.*;

Import Org.json.JSONObject;  public class Healthserverhandler extends Channelinboundhandleradapter {private static final asciistring Content_Type
    = new Asciistring ("Content-type");
    private static final asciistring content_length = new Asciistring ("Content-length"); private static final asciistring CONnection = new Asciistring ("Connection");

    private static final asciistring keep_alive = new Asciistring ("keep-alive");
    @Override public void Channelreadcomplete (Channelhandlercontext ctx) {Ctx.flush (); @Override public void Channelread (Channelhandlercontext ctx, Object msg) {if (msg instanceof fullhttp Request) {Fullhttprequest req = (fullhttprequest) msg;//client's requested object Jsonobject = new JS
            Onobject ();//New JSON object that returns the message format the request data of the client as a JSON object jsonobject Requestjson = null;
            try{Requestjson = new Jsonobject (Parsejosnrequest (req));
                }catch (Exception e) {Responsejson (ctx,req,new String ("error JSON"));
            Return The String uri = Req.uri ()//Gets the URL of the client///(routing distribution) for the different request APIs, only the Post method if (Req.meth OD () = = Httpmethod.post) {if (Req.uri (). Equals ("/bmi) {//Weight mass index double height =0.01* requestjson.getdouble ("Heig
                    HT ");
                    Double weight =requestjson.getdouble ("weight");
                    Double BMI =weight/(height*height);
                    BMI = ((int) (bmi*100))/100.0;

                Responsejson.put ("BMI", BMI + ""); }else if (Req.uri (). Equals ("/BMR")) {//Calculate the Basal metabolic Rate Boolean isboy = req
                    Uestjson.getboolean ("Isboy");
                    Double height = requestjson.getdouble ("height");
                    Double weight = requestjson.getdouble ("Weight");
                    int age = Requestjson.getint (' age ');
                    Double bmr=0;
                        if (isboy) {//66 + (13.7 x weight kg) + (5 x Height cm)-(6.8 x Age years)

                    BMR = 66+ (13.7*weight) + (5*height)-(6.8*age);
               }else     {//655 + (9.6 x weight kg) + (1.8 x Height cm)-(4.7 x Age years) BMR =65
                    5 + (9.6*weight) +1.8*height-4.7*age;
                    } BMR = ((int) (bmr*100))/100.0;
                Responsejson.put ("BMR", bmr+ "");
                }else {//Error handling Responsejson.put ("error", "404 Not Find");
            } else {//Error handling Responsejson.put ("error", "404 Not Find");
        //Send results to Client (ctx,req,responsejson.tostring () Responsejson); }/** * Response to HTTP request * @param CTX * @param req * @param jsonstr/private void Respo Nsejson (Channelhandlercontext ctx, fullhttprequest req, String jsonstr) {Boolean keepAlive = Httputil.iskeep
        Alive (req);
        byte[] Jsonbytebyte = Jsonstr.getbytes (); Fullhttpresponse response = new Defaultfullhttpresponse (HTTP_1_1, OK, Unpooled.wrappedbuffer (Jsonbytebyte));
        Response.headers (). Set (Content_Type, "Text/json");

        Response.headers (). Setint (Content_length, Response.content (). Readablebytes ());
        if (!keepalive) {ctx.write (response). AddListener (Channelfuturelistener.close);
            else {response.headers (). Set (CONNECTION, keep_alive);
        Ctx.write (response); @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {CAUSE.PRINTST
        Acktrace ();
    Ctx.close ();  /** * Get the requested content * @param request * @return/private String parsejosnrequest (fullhttprequest
        Request) {Bytebuf jsonbuf = request.content ();
        String jsonstr = jsonbuf.tostring (charsetutil.utf_8);
    return jsonstr;
 }
}
5 Run Test

In Eclipse, you can open the Netty service directly by Run as Java application. Netty services do not need to be placed in any container and can be run separately.

Google's postman test is used here.

6 export Jar

The Netty service cannot run as application in eclipse only when it is released out of the box. So when you publish a service, you need to export the jar that runs, and then run the jar file.

Right-click the current project->export-> in Eclipse Select the runnable Jar file->next under the Java option in the Export window-> Select the exported file path and the initiated entry class in the window- > Finish.

Open the command line terminal, switch to the current directory, execute Java-jar server.jar, and you can start the service (Server.jar is the derived jar). Can be tested by postman. 7 to deploy the code on the VPS

The restful service that is actually used needs to be deployed on a server. Here I put the Server.jar deployed on the bricklayer VPS. The VPS installation system is CentOS 6 x86 minimal. The system itself does not have a JDK installed and needs to be installed via the Yum command openjdk.

The Yum list java* lists all OPENJDK versions. This is where jdk1.8 yum install java-1.8.0-openjdk.i686 is installed via Yum to view the java-version version through the OPENJDK command.

Server.jar can be uploaded via the SFTP VPS server, which uses Cyberduck software under this Mac system. Or you can upload the jar to the VPS server through the Linux SCP command, which can refer to http://blog.csdn.net/marujunyy/article/details/8809481

The Linux command Line window is actually a single task mode, and if you run the jar directly, the jar will be turned off automatically and will not reside on the server for long. Screen This multiple window management software (which can be installed via Yum) is required.

Screen-s Healthserver opens a new window, executes the Java-jar Server.jar run the service, so that the service can run as a stand-alone task running separately . You can switch back to the main window through the shortcut key ctl+a+d.

The SCREEN-LS command lists all currently available window tasks. The Screen-r healthserver command switches to the window where the service runs. 8 The end

The final interface can be tested by postman. 9 Reference official website http://netty.io/"Netty actual combat (Essence)" https://waylau.gitbooks.io/essential-netty-in-action/content/ Getting%20started/introducing%20netty.html Netty Build Game server https://my.oschina.net/acitiviti/blog/745206

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.