我查看了 Netty 文档,并在示例源类中找到了一些注释: org.jboss.netty.example.factorial.FactorialServerHandler ,在此 src 中,一些注释:
//##in org.jboss.netty.example.factorial.FactorialServerPipelineFactory
......
// and then business logic.
// Please note we create a handler for every new channel
// because it has stateful properties.
pipeline.addLast("handler", new FactorialServerHandler());
但是,我重新检查了其他示例,例如 TelnetServerPipelineFactory,似乎没有什么区别,句柄是通过以下方式创建的:
// and then business logic.
pipeline.addLast("handler", new TelnetServerHandler());
所有的处理程序都是由管道用“new”创建的? Netty 中的所有示例都是有状态的?显然 Echo/Telnet 不需要保留有状态的属性。
在我的旧项目中,我使用 Netty 创建一个 Http Server 来充当 RESTful 服务器,我的处理程序代码是:
public class HttpServerPipelineFactory implements ChannelPipelineFactory {
private final HttpServerHandler handler;
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("handler", handler); //singleton
return pipeline;
}
}
我的 RESTful 服务器是无状态的(这是 REST 含义之一),所以我使用了单例句柄。我说得对吗?
最佳答案
当文档说“有状态”时,这意味着状态信息作为字段存储在 ChannelHandler 中,因此不可能在不同 Channel 之间共享 ChannelHandler。如果您没有存储为字段的状态信息,您可以将其用作 Singelton。
关于java - 有状态 xxxServerHandle 和无状态 yyyServerhandle 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10274293/