EventLoopGroup和BIO操作。

时间:2013-06-05 22:17:53

标签: netty

我正在使用Netty Web服务器,它应该使用Hibernate检索数据并将响应返回给客户端。

所以我只是想知道我的实现是否正确

   ChannelPipeline pipeline = ch.pipeline();
        EventExecutorGroup ex = new DefaultEventExecutorGroup(64);

        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

        pipeline.addLast(ex,"handler", new HttpWebServerHandler());

然后在messageReceived方法内部:

    @Override
    public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request)
            throws Exception {
         if (!request.getDecoderResult().isSuccess()) {
                sendError(ctx, BAD_REQUEST);
                return;
            }
          ctx.executor().execute(new MyRunnable(ctx)); 
    }

并且在Runnable中:

@Override
public void run() {

        SomeObejct so = HibernateTemplate.getSomeObject() ;
                    String serializedSo = serialize(so);
          FullHttpResponse res = new DefaultFullHttpResponse(
                    HTTP_1_1, OK, Unpooled.copiedBuffer(serializedSo, CharsetUtil.UTF_8));
            res.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");                      ctx.write(res).addListener(ChannelFutureListener.CLOSE);     
}

我做得对吗?

1 个答案:

答案 0 :(得分:1)

是的,这看起来是正确的。您可能想要考虑的是从ChannelPipeline中删除HttpObjectAggregator,从而节省一些内存开销。但请注意,您需要自己处理不同的HTTP消息部分。