1

也许这是一个明显的问题,但我对 netty 太陌生了。

看看 HttpChunckAggregator 类,我发现它是有状态的。这让我怀疑......给定一个具有以下管道的特定频道:

private MyServerHandler handler;

public ChannelPipeline getPipeline() throws Exception {
    ChannelPipeline pipeline = pipeline();                   
    pipeline.addLast("decoder",new HttpRequestDecoder());       
    pipeline.addLast("chunkAggregator",new HttpChunkAggregator(4194304));       
    pipeline.addLast("encoder",new HttpResponseEncoder());              
    pipeline.addLast("chunkSeparator",new HttpChunkSeparator(4194304));         
    pipeline.addLast("handler", handler); //Singleton       
    return pipeline;
}

和 NIO Netty 服务器,在分块消息和多线程的情况下,我可以获得竞争条件吗?

我看到每个新频道都会创建一个新的块聚合器,但是......所有的块消息都将在同一个频道中接收?

4

2 回答 2

1

它是安全的,因为它不被不同的频道共享。在 netty 中,只有一个线程正在执行上游事件,因此只要不从下游事件访问/修改这些状态​​,就可以安全地将状态存储在字段中而无需任何同步。

于 2012-08-02T12:11:52.077 回答
1

每个传入消息都会调用 getPipeline。因此,对于每个 HttpRequest,您将创建一个新的 HttpChunkSeparator。

但是,如果您做了这样的事情,那将是完全不安全的线程。

private MyServerHandler handler;

// THIS IS WRONG AS getPipeline() will keep giving the same instance to multiple threads.
private HttpChunkAggregator httpChunkAggregator;

public ChannelPipeline getPipeline() throws Exception {
    ChannelPipeline pipeline = pipeline();                   
    pipeline.addLast("decoder",new HttpRequestDecoder()); 

    // This is WRONG. DO NO DO THIS. INSTEAD DO new HttpChunkAggregator().      
    pipeline.addLast("chunkAggregator",httpChunkAggregator);      

    pipeline.addLast("encoder",new HttpResponseEncoder());              
    pipeline.addLast("chunkSeparator",new HttpChunkSeparator(4194304));         
    pipeline.addLast("handler", handler); //Singleton       
    return pipeline;
}

阿伦

于 2013-04-16T14:45:16.333 回答