乐趣区

关于java:搭建一个简单高效的http服务

首先引入 netty 依赖

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.72.Final</version>
</dependency>

而后是一个简略的测试类

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<Channel>() {

                    @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<FullHttpRequest> {

    @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();
            }
        });

    }

}

启动服务,实现!

退出移动版