搭建一个简单高效的http服务

首先引入netty依赖


    io.netty
    netty-all
    4.1.72.Final

然后是一个简单的测试类

public class App {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new ChannelInitializer() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new HttpObjectAggregator(1 * 1024 * 1024));
                        ch.pipeline().addLast(new HttpHandler());

                    }

                }).bind(1601).sync().channel().closeFuture().sync();

    }
}

class HttpHandler extends SimpleChannelInboundHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        boolean success = request.decoderResult().isSuccess();
        System.out.println(success);
        ByteBuf bb1 = Unpooled.wrappedBuffer("北京欢迎你\n".getBytes());
        ByteBuf bb2 = Unpooled.wrappedBuffer("为你开天辟地\n".getBytes());
        ByteBuf target = Unpooled.wrappedBuffer(bb1, bb2);
        FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, target);
        fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
        ctx.writeAndFlush(fullHttpResponse).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                ctx.close();
            }
        });

    }

}

启动服务,完成!

你可能感兴趣的:(java)