0

我有 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);     
}

我做对了吗?

4

1 回答 1

1

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

于 2013-06-06T06:21:42.543 回答