当前位置: 移动技术网 > IT编程>开发语言>Java > Java Netty HTTP服务实现过程解析

Java Netty HTTP服务实现过程解析

2020年08月17日  | 移动技术网IT编程  | 我要评论
超文本传输协议(http,hypertext transfer protocol)是互联网上应用最为广泛的一种网络协议。在后端开发中接触http协议的比较多,目前大部分都是基于servlet容器实现的

超文本传输协议(http,hypertext transfer protocol)是互联网上应用最为广泛的一种网络协议。

在后端开发中接触http协议的比较多,目前大部分都是基于servlet容器实现的http服务,往往有一些核心子系统对性能的要求非常高,这个时候我们可以考虑采用nio的网络模型来实现http服务,以此提高性能和吞吐量,netty除了开发网络应用非常方便,还内置了http相关的编解码器,让用户可以很方便的开发出高性能的http协议的服务,spring webflux默认是使用的netty。

接下来我们简单的介绍下如何使用netty来构建一个简单的http服务

创建一个nettyhttpserver来启动服务

public static void main(string[] args) {
  int port = 2222;
  new nettyhttpserver().run(port);
}

public void run(int port) {
  eventloopgroup bossgroup = new nioeventloopgroup();
  eventloopgroup workergroup = new nioeventloopgroup();
  serverbootstrap bootstrap = new serverbootstrap();
  bootstrap.group(bossgroup, workergroup).channel(nioserversocketchannel.class)
      .childhandler(new channelinitializer<socketchannel>() {
        @override
        public void initchannel(socketchannel ch) throws exception {
            ch.pipeline().addlast(
                new httpresponseencoder(),
                new httprequestdecoder(),
                new nettyhttpserverhandler());
        }
        }).option(channeloption.so_backlog, 128)
        .childoption(channeloption.so_keepalive, true);
  try {
    channelfuture f = bootstrap.bind(port).sync();
    f.channel().closefuture().sync();
  } catch (interruptedexception e) {
    e.printstacktrace();
  } finally {
    workergroup.shutdowngracefully();
    bossgroup.shutdowngracefully();
  }
}

需要关注的是下面的这行代码:

ch.pipeline().addlast(
new httpresponseencoder(),
new httprequestdecoder(),
new nettyhttpserverhandler());

httpresponseencoder: 服务端往客户端发送数据的行为是response,所以这边要使用httpresponseencoder将数据进行编码操作

httprequestdecoder:服务端接收到数据的行为是request,所以要使用httprequestdecoder进行解码操作

nettyhttpserverhandler:自定义的数据处理类

public class nettyhttpserverhandler extends channelinboundhandleradapter {

public class nettyhttpserverhandler extends channelinboundhandleradapter {

  @override
  public void channelread(channelhandlercontext ctx, object msg) throws exception {  
    fullhttpresponse response = new defaultfullhttpresponse(
        httpversion.http_1_1, 
        httpresponsestatus.ok,
        unpooled.wrappedbuffer("欢迎来到猿天地".getbytes("utf-8")));
    response.headers().set(names.content_type, "text/plain;charset=utf-8");
    response.headers().set(names.content_length, response.content().readablebytes());
    response.headers().set(names.connection, values.keep_alive);
    ctx.write(response);
    ctx.flush();
  }

  @override
  public void channelreadcomplete(channelhandlercontext ctx) throws exception {
    ctx.flush();
  }

  @override
  public void exceptioncaught(channelhandlercontext ctx, throwable cause) throws exception {
    ctx.close();
    cause.printstacktrace();
  }

}

通过defaultfullhttpresponse构建了返回的对象,设置了http版本,返回的状态码,返回的内容。

返回的响应头通过response.headers().set()进行设置。

到此为止,一个简单的http服务就实现好了,我们启动服务,在浏览器中输入http://localhost:2222/ 就可以看到页面中显示的内容是:欢迎来到猿天地

上面演示的是一个典型的请求响应模式,一般我们开发接口的时候通常都是需要根据请求的参数进行对应的数据返回,如何在netty中获取请求的参数呢?

channelread方法中的msg参数就是请求信息,通过msg可以获取到请求的所有信息,有请求头信息(包括请求的地址,get请求的参数),请求体(post请求的数据)。

下面已get请求的方式来获取请求的参数信息,代码如下:

if (msg instanceof httprequest) {
    defaulthttprequest request = (defaulthttprequest) msg;
    system.out.println("uri:" + request.geturi());
    system.err.println(msg);
}
if (msg instanceof httpcontent) {
    lasthttpcontent httpcontent = (lasthttpcontent) msg;
    bytebuf bytedata = httpcontent.content();
    if (bytedata instanceof emptybytebuf) {
      system.out.println("content:无数据");
    } else {
      string content = new string(byteutils.objecttobyte(bytedata));
      system.out.println("content:" + content);
    }
}

重启服务,访问地址加上参数进行访问:http://localhost:2222/?name=yjh

可以看到控制台输出的内容就是一个完整的http请求包含的信息:

uri:/?name=yjh
defaulthttprequest(decoderesult: success, version: http/1.1)
get /?name=yjh http/1.1
host: localhost:2222
connection: keep-alive
upgrade-insecure-requests: 1
user-agent: mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/64.0.3282.186 safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding: gzip, deflate, br
accept-language: zh-cn,zh;q=0.9
cookie: _ga=ga1.1.939107719.1520393952; jsessionid=ee205236911d5bba145e3021db472d90
content:无数据

本文只是简单的介绍了如何在netty中去实现http服务,如果想要做成spring mvc这样的框架那后面的路还很长,请求响应netty内置了编解码器,还是有很多工作需要自己去做的。比如参数的获取,请求的路由,参数映射成对象等….

源码参考:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网