如何使用Netty 4编写基于SEDA的Http Server?

时间:2019-07-17 11:31:29

标签: java netty

我正在尝试使用Netty编写基于暂存事件驱动的体系结构(SEDA)的简单Http Server。我想出了以下代码作为基本的NIO代码。

EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

try {
    ServerBootstrap bootstrap = new ServerBootstrap()
        .group(eventLoopGroup)
        .handler(new LoggingHandler(LogLevel.INFO))
        .childHandler(new HttpServerInitializer())
        .channel(NioServerSocketChannel.class);

    Channel ch = bootstrap.bind(HTTP_PORT).sync().channel();
    ch.closeFuture().sync();
} finally {
    eventLoopGroup.shutdownGracefully();
}
public class HttpServerInitializer extends ChannelInitializer<Channel> {

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpServerHandler());
    }
}
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof LastHttpContent) {
            ByteBuf content = Unpooled.copiedBuffer("Hello World.", CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
            ctx.write(response);
        }
    }

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

This是与Netty的SEDA相关的GitHub问题,但未提供有关如何在NIO中使用SEDA的文档。

This说,可以通过向管道添加多个ExecutionHandler来实现另一种线程模型,例如SEDA。但是ExecutionHandler在Netty 4中似乎不可用。

0 个答案:

没有答案