本文介绍了工作线程在Netty被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道netty使用Reactor模式来避免为​​每个连接创建一个线程
关于这个模式的核心概念是选择器或 epoll Linux中的系统调用。

I know netty uses the Reactor pattern to avoid creating a thread for each connection,the core concept about this pattern is a "selector" or epoll system call in Linux.

但是我也听说过,如果处理程序从不关闭它的通道,它将占用一个工作线程并阻塞它:这并不意味着每个连接将使用(块) )一个线程,所以对于每个接受的套接字,我们仍然需要创建一个线程吗?

But I also heard about that if a handler never close it's channel, it will occupy one worker thread and block it: doesn't that mean each connetion will use (block) one thread,so for each accepted socket we still need to create a thread ?

例如,如果我写一个10,000持久的服务器连接,这台服务器需要10000个工作线程吗?

for example ,if I write a server with 10,000 persistent connections,does this server need 10,000 worker threads??

上述两件事之间的矛盾使我感到困惑,任何人都可以解释我,如果我理解错了吗?谢谢〜

The contradiction between those two things above confused me ,can anyone explain me if I understand it wrong? thank you~

================================ ========

========================================

一个示例(只有一个工作线程),可以始终同时处理一个客户端的事件。

an example (with only 1 worker thread ) which can always process one client's event in the same time.

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class Netty_test {
    public static void main(String[] args) {
        ChannelFactory factory =new     NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newFixedThreadPool(1));
    ServerBootstrap bootstrap = new ServerBootstrap(factory);
        ChannelPipelineFactory cpf=new ChannelPipelineFactory(){
            public ChannelPipeline getPipeline() {
                return Channels.pipeline(new testHandler());
            }
        };
        bootstrap.setPipelineFactory(cpf);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.bind(new InetSocketAddress(100));
    }
}
class testHandler extends SimpleChannelHandler {
@Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        System.out.println("messageReceived, handler work.");
        e.getChannel().write(e.getMessage());
        ctx.sendUpstream(e);
    }
}


推荐答案

否,您的10,000个连接将共享工作线程。一个工作线程将处理多个连接/通道。这就是为什么不阻止工作线程非常重要的原因。

No, your 10,000 connections will share the worker threads. One worker thread will handle multiple connections/channels. This is why it is very important not to block the worker threads.

这篇关于工作线程在Netty被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:48
查看更多