Netty搭建Http服务端

/ Netty / 没有评论 / 37浏览

采用Netty4.x搭建Http服务端。

Bootstrap

public class HttpServer {

    private static final Logger LOG = LoggerFactory.getLogger(HttpServer.class);

    private volatile boolean running;

    private HttpPipelineInitializer initializer = new HttpPipelineInitializer();

    public HttpServer() {
    }

    public void listenAndServe(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(initializer);

            Channel ch = bootstrap.bind(port).sync().channel();

            running = true;
            LOG.info("listen port: {}", port);

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            running = false;
        }
    }

    public boolean isRunning() {
        return running;
    }

    public void setInitializer(HttpPipelineInitializer initializer) {
        this.initializer = initializer;
    }
}

Initializer

public class HttpPipelineInitializer extends ChannelInitializer<Channel> {

    private static final int MAX_SIZE = 512 * 1024;

    @Override
    protected void initChannel(Channel channel) {
        ChannelPipeline pipeline = channel.pipeline();
        // combination of HttpRequestDecoder and HttpResponseEncoder
        pipeline.addLast(new HttpServerCodec());
        // aggregates an HttpMessage and its following HttpContent into a single FullHttpRequest
        pipeline.addLast(new HttpObjectAggregator(MAX_SIZE));
        pipeline.addLast(new HttpServerHandler());
    }
}

Handler

public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger LOG = LoggerFactory.getLogger(HttpServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
        // 处理请求
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOG.warn("exceptionCaught", cause);
        ctx.close();
    }
}

启动

public class App {
    public static void main(String[] args) {
		try {
		    new HttpServer().listenAndServe(9000);
		} catch (Exception e) {
		    LOG.error("listenAndServe error.", e);
		}
    }
}