也许这是一个明显的问题,但我对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服务器,我可以在分块消息和多线程的情况下获得竞争条件吗?
我看到每个新频道都会创建一个新的块聚合器但是......所有的块消息都会在同一个频道中收到?
答案 0 :(得分:1)
它不安全,因为它不被不同频道共享。在netty中,只有一个线程正在执行上游事件,因此只要不从下游事件访问/修改这些状态,就可以安全地在没有任何同步的字段中存储状态。
答案 1 :(得分:1)
为每个传入消息调用getPipeline。因此,对于每个HttpRequest,您将创建一个新的HttpChunkSeparator。
如果你做了这样的事情,它将完全是线索UNSAFE。
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;
}
阿伦