문제

I reviewed Netty docs, and found some comments in examples source Class: org.jboss.netty.example.factorial.FactorialServerHandler , in this src, some comments:

    //##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());

But, I recheck other examples, such as TelnetServerPipelineFactory, seems nothing difference, the handle is create by:

    // and then business logic. 
    pipeline.addLast("handler", new TelnetServerHandler());

All the handlers are created by pipeline with "new"? And all the examples in Netty are stateful? Obviously Echo/Telnet needn't keep stateful prop.

In my old project, I use Netty to create a Http Server to act as RESTful server, my handler code is:

    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;
        }
    }

My RESTful server is statefulless(which is one of REST meaning), so I used singleton handle. Was I right?

도움이 되었습니까?

해결책

When the documentation says "stateful" it means that state informations are stored as fields in the ChannelHandler and thus its not possible to share the ChannelHandler between different Channels. If you have no state informations stored as fields you are ok to use it as Singelton.

다른 팁

You don't have a reason to instantiate new handlers if they are stateless. But in Http examples those handlers are stateful. They receive frame by frame from network and parse them into headers and what-not. Then if request is chunked, Aggregator is combining chunks into single payload, etc. In short, unless you are building an echo server, lower level handlers probably must be stateful, but higher level need not.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top