Skip to content

Tomcat连接器 ​

深入理解Tomcat连接器的实现,掌握NIO、NIO2等连接器的原理,理解连接管理、性能优化等核心机制。

📋 连接器概览 ​

连接器是Tomcat处理网络请求的组件,负责接收请求和发送响应。

🎯 一、NIO连接器 ​

1.1 NioEndpoint ​

NioEndpoint:

java
public class NioEndpoint extends AbstractEndpoint<NioChannel> {
    
    private Selector selector = null;
    private Poller[] pollers = null;
    private int pollerThreadCount = 
            Math.min(2, Runtime.getRuntime().availableProcessors());
    
    @Override
    public void startInternal() throws Exception {
        if (!running) {
            running = true;
            paused = false;
            
            processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                    socketProperties.getProcessorCache());
            eventCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                    socketProperties.getEventCache());
            nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
                    socketProperties.getBufferPool());
            
            selectorPool.open();
            
            startAcceptorThreads();
            
            pollers = new Poller[getPollerThreadCount()];
            for (int i = 0; i < pollers.length; i++) {
                pollers[i] = new Poller();
                Thread pollerThread = new Thread(pollers[i], getName() + 
                        "-ClientPoller-" + i);
                pollerThread.setPriority(threadPriority);
                pollerThread.setDaemon(true);
                pollerThread.start();
            }
        }
    }
}

1.2 Poller ​

Poller.run:

java
@Override
public void run() {
    while (true) {
        boolean hasEvents = false;
        try {
            if (!close) {
                hasEvents = events();
            }
            if (close) {
                events();
                timeout(0, false);
                try {
                    selector.close();
                } catch (Exception ignore) {
                }
                break;
            }
        } catch (Throwable x) {
            // ...
        }
        if (keyCount == 0) {
            synchronized (this) {
                if (events.size() == 0 && close) {
                    break;
                }
            }
        }
    }
}

🎯 二、连接管理 ​

2.1 连接池 ​

连接池管理:

  • 连接创建:按需创建连接
  • 连接复用:复用现有连接
  • 连接关闭:连接关闭和清理

2.2 连接超时 ​

连接超时处理:

java
protected void timeout(int keyCount, boolean hasEvents) {
    long now = System.currentTimeMillis();
    if (nextExpiration > 0 && (keyCount > 0 || hasEvents) && 
            (now - nextExpiration) < 0) {
        return;
    }
    int keycount = 0;
    try {
        for (SelectionKey key : selector.keys()) {
            keycount++;
            try {
                NioSocketChannel socketChannel = (NioSocketChannel) key.attachment();
                if (socketChannel == null) {
                    cancelledKey(key);
                } else if (socketChannel.asyncReadBuffer != null) {
                    long delta = now - socketChannel.getLastRead();
                    long timeout = socketChannel.getReadTimeout();
                    if (timeout > 0 && delta > timeout) {
                        key.interestOps(0);
                        socketChannel.setTimedOut(true);
                        keycount--;
                        processKey(key, socketChannel);
                    }
                }
            } catch (CancelledKeyException ckx) {
                cancelledKey(key);
            }
        }
    } catch (ConcurrentModificationException cme) {
        // ...
    }
    if (keycount > 0 || hasEvents) {
        nextExpiration = System.currentTimeMillis() + 
                socketProperties.getTimeoutInterval();
    }
}

📖 学习资源 ​

视频教程 ​

书籍推荐 ​

  • 《Tomcat架构解析》 - 刘光瑞

网站资源 ​

✅ 学习检查清单 ​

  • [ ] 已理解NIO连接器实现
  • [ ] 已理解连接管理机制
  • [ ] 已理解性能优化
  • [ ] 已总结核心知识点

上一章节:Tomcat请求处理
下一章节:Tomcat容器架构
返回目录:Mybatis和Tomcat源码深度解析