netty服务器搭建-http

来源:互联网 发布:手机千牛淘宝客插件 编辑:程序博客网 时间:2024/05/22 12:05

此处首先声明是Netty5.x版本的jar包搭建的http服务器!
首先初始化channel,绑定端口,启动服务;再者对客户端请求进行逻辑业务处理,随后响应;
话不多说,直接见代码讲:

protected void initChannel(SocketChannel ch) throws Exception {        //老板接到任务分配给员工        EventLoopGroup bossGroup = new NioEventLoopGroup();   //创建接收客户端请求连接的线程池---老板        EventLoopGroup  workerGroup = new NioEventLoopGroup();   //用来处理bossGroup(老板)中的连接数据的线程池---员工        try {            //通过ServerBootstrap对象启动服务器            ServerBootstrap b = new ServerBootstrap();            //ByteBuf数据结构创建方式            //UnpooledByteBufAllocator的方式创建ByteBuf的时候,单台24核CPU的服务器,16G内存,刚启动时候,10000个长连接,每隔几秒就发一条群组消息,内存占到10G多点,但随着系统的运行,内存不断增长,直到整个系统内存溢出挂掉。            //把UnpooledByteBufAllocator换成PooledByteBufAllocator,内存使用量机器能维持在一个连接占用0.9-1M之间,经常长期的运行测试,发现都能维持在这个数量            b.group(bossGroup, workerGroup)    //设置bossGroup与workerGroup俩个线程,处理请求的任务            .channel(NioServerSocketChannel.class)               .option(ChannelOption.SO_BACKLOG, 1024)   //设置俩线程的最大容纳量            .option(ChannelOption.TCP_NODELAY, true)  //设置封包 使用一次大数据的写操作,而不是多次小数据的写操作,批量操作            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)   //设置ByteBuf数据结构的创建方式PooledByteBufAllocator(5.x版本PooledByteBufAllocator作为默认的buffer allocator)            .childHandler(new ChannelInitializer<SocketChannel>() {                @Override                protected void initChannel(SocketChannel ch) throws Exception {                    //聚合器                    //一般http请求或者响应,解码器都将其解码成为多个消息对象,主要是httpRequest/httpResponse, httpcontent, lastHttpContent.然后反复调用方法,                    //HttpObjectAggregator 这个handler就是将同一个http请求或响应的多个消息对象变成一个 fullHttpRequest完整的消息对象                    ch.pipeline().addLast("decoder", new HttpRequestDecoder());   //添加解码器                    ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));   //添加聚合器                    ch.pipeline().addLast("encoder", new HttpResponseEncoder());  //添加编码器                    ch.pipeline().addLast("deflater", new HttpContentCompressor());  //添加压缩器                    ch.pipeline().addLast("handler", null);   //添加处理任务的handler                }            });             b.bind(PORT).sync().channel().closeFuture().sync();    //绑定端口,并启动服务监听        } catch (Exception e) {        } finally {            //关闭所有事件循环终止线程            workerGroup.shutdownGracefully();                 bossGroup.shutdownGracefully();        }    }public class ServerHandler extends ChannelHandlerAdapter {         //@Sharable根据业务需要,来决定handler是否共享    //5.x版本整合成ChannelHandlerAdapter    //keepAlive  设置是否长连接       private HttpRequest request;    /**     * 请求处理完最后执行     */    @Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        System.out.println("i am coming channelReadComplete");        ctx.flush();    }    /**     * 处理http请求     */    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg)            throws Exception {        System.out.println("msg is:"+msg);        System.out.println("i am coming channelRead");        if (msg instanceof HttpRequest) {            request = (HttpRequest) msg;            /**             * 100 Continue             * 是这样的一种情况:HTTP客户端程序有一个实体的主体部分要发送给服务器,但希望在发送之前查看下服务器是否会             * 接受这个实体,所以在发送实体之前先发送了一个携带100             * Continue的Expect请求首部的请求。服务器在收到这样的请求后,应该用 100 Continue或一条错误码来进行响应。             */            if(HttpHeaders.is100ContinueExpected(request)){                ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));            }        }    //一般http请求或者响应,解码器都将其解码成为多个消息对象,主要是httpRequest/httpResponse, httpcontent, lastHttpContent.然后反复调用方法,         if (msg instanceof HttpContent) {            /*逻辑处理*/        }        if (msg instanceof LastHttpContent) {        //业务处理逻辑最好写在此处,此处确保请求到了最后            /*逻辑处理*/        }    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)            throws Exception {        System.out.println("i am coming exceptionCaught");        ctx.close();        //super.exceptionCaught(ctx, cause);    }}
0 0
原创粉丝点击