引入 Executor在哪里启动线程池? Request是如何处理并交给Container的? Tomcat支持哪些协议?这些协议是处理的?如何设计协议层次结构? Connector Conector构造
本质是ProtocolHandler的初始化,默认为HTTP/1.1.1 NIO实现。 /** * Defaults to using HTTP/1.1 NIO implementation. */ public Connector() { this("HTTP/1.1"); } public Connector(String protocol) { boolean apr = AprStatus.isAprAvailable() && AprStatus.getUseAprConnector(); ProtocolHandler p = null; try { p = ProtocolHandler.create(protocol, apr); } catch (Exception e) { log.error(sm.getString( "coyoteConnector.protocolHandlerInstantiationFailed"), e); } if (p != null) { protocolHandler = p; protocolHandlerClassName = protocolHandler.getClass().getName(); } else { protocolHandler = null; protocolHandlerClassName = protocol; } // Default for Connector depends on this system property setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")); }
ProtocolHandler是如何通过protocol初始化实现的?让我们看看ProtocolHandler.create(protocol, apr) public static ProtocolHandler create(String protocol, boolean apr) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { if (protocol == null || "HTTP/1.1".equals(protocol) || (!apr && org.apache.coyote.http11.NioProtocolHttp11.class.getName().equals(protocol)) || (apr && org.apache.coyote.http11.AprotocolHttp11.class.getName().equals(protocol))) { if (apr) { return new org.apache.coyote.http11.AprotocolHttp11(); } else { return new org.apache.coyote.http11.NioProtocolHttp11(); } } else if ("AJP/1.3".equals(protocol) || (!apr && org.apache.coyote.ajp.AjpNioProtocol.class.getName().equals(protocol)) || (apr && org.apache.coyote.ajp.AjpAprProtocol.class.getName().equals(protocol))) { if (apr) { return new org.apache.coyote.ajp.AjpAprProtocol(); } else { return new org.apache.coyote.ajp.AjpNioProtocol(); } } else { // Instantiate protocol handler Class clazz = Class.forName(protocol); return (ProtocolHandler) clazz.getConstructor().newInstance(); } }
通过Protocol,我们可以看到上述方法实际上初始化了ProtocolHandler, 让我们来看看它支持的HTTP1.1和Ajp协议的处理。我们通过其层次结构来看待协议支持处理

connector初始化
JMX的初始模板方法initInternal在Connector的初始化中,它做了什么? adapter初始化给protocolHandler ///这个adapter是真正连接container处理的适配器,后面我们会详细解释。 默认为POST方法设置parsebody的方法 一些校验 调用protocolHandler的init @Override protected void initInternal() throws LifecycleException { super.initInternal(); if (protocolHandler == null) { throw new LifecycleException( sm.getString("coyoteConnector.protocolHandlerInstantiationFailed")); } // 初始化 adapter adapter = new CoyoteAdapter(this); protocolHandler.setAdapter(adapter); // 交给protocolHandler if (service != null) { protocolHandler.setUtilityExecutor(service.getServer().getUtilityExecutor()); } // 默认为POSTT设置parseBody的方法 if (null == parseBodyMethodsSet) { setParseBodyMethods(getParseBodyMethods()); } // 校验 if (protocolHandler.isAprRequired() && !AprStatus.isInstanceCreated()) { throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerNoAprListener", getProtocolHandlerClassName())); } if (protocolHandler.isAprRequired() && !AprStatus.isAprAvailable()) { throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerNoAprLibrary", getProtocolHandlerClassName())); } if (AprStatus.isAprAvailable() && AprStatus.getUseOpenSSL() && protocolHandler instanceof Abstracthttp11Jsseprotocol { Http11JsseProtocolotof11Abstract jsseProtocolHandler = (AbstractHttp11JsseProtocolp11) protocolHandler; if (jsseProtocolHandler.isSSLEnabled() && jsseProtocolHandler.getSslImplementationName() == null) { // OpenSSL is compatible with the JSSE configuration, so use it if APR is available jsseProtocolHandler.setSslImplementationName(OpenSSLImplementation.class.getName()); } } try { // inittt,调用protocolHandler protocolHandler.init(); } catch (Exception e) { throw new LifecycleException( sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e); } }
protocolHandlerinit做了什么?本质上,Abstractendpointinit方法被调用 /** * Endpoint that provides low-level network I/O - must be matched to the * ProtocolHandler implementation (ProtocolHandler using NIO, requires NIO * Endpoint etc.). */ private final AbstractEndpoint endpoint; @Override public void init() throws Exception { if (getLog().isInfoEnabled()) { getLog().info(sm.getString("abstractProtocolHandler.init", getName())); logPortOffset(); } if (oname == null) { // Component not pre-registered so register it oname = createObjectName(); if (oname != null) { Registry.getRegistry(null, null).registerComponent(this, oname, null); } } if (this.domain != null) { rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName()); Registry.getRegistry(null, null).registerComponent( getHandler().getGlobal(), rgOname, null); } String endpointName = getName(); endpoint.setName(endpointName.substring(1, endpointName.length()-1)); endpoint.setDomain(domain); endpoint.init(); }
endpoint.init()你做了什么?在之前的版本中,bind方法被直接调用到bindWithCleanup, 变化点在于失败后的清洁操作。 public final void init() throws Exception { if (bindOnInit) { bindWithCleanup(); // 看这里 bindState = BindState.BOUND_ON_INIT; } // 以下是注册JMX。我们在前面谈过。 if (this.domain != null) { // Register endpoint (as ThreadPool - historical name) oname = new ObjectName(domain + ":type=ThreadPool,name=\"" + getName() + "\""); Registry.getRegistry(null, null).registerComponent(this, oname, null); ObjectName socketPropertiesOname = new ObjectName(domain + ":type=SocketProperties,name=\"" + getName() + "\""); socketProperties.setObjectName(socketPropertiesOname); Registry.getRegistry(null, null).registerComponent(socketProperties, socketPropertiesOname, null); for (SSLHostConfig sslHostConfig : findSslHostConfigs()) { registerJmx(sslHostConfig); } } }
bindWithCleanup()做bind方法,如果绑定失败,回调unbind方法。 private void bindWithCleanup() throws Exception { try { bind(); } catch (Throwable t) { // Ensure open sockets etc. are cleaned up if something goes // wrong during bind ExceptionUtils.handleThrowable(t); unbind(); throw t; } }
bind()方法是初始ServerSocket和初始ssl /** * Initialize the endpoint. */ @Override public void bind() throws Exception { initServerSocket(); setStopLatch(new CountDownLatch(1)); // Initialize SSL if needed initialiseSsl(); selectorPool.open(getName()); } // Separated out to make it easier for folks that extend NioEndpoint to // implement custom [server]sockets protected void initServerSocket() throws Exception { if (!getUseInheritedChannel()) { serverSock = ServerSocketChannel.open(); // 打开Serversocket通道 socketProperties.setProperties(serverSock.socket()); InetSocketAddress addr = new InetSocketAddress(getAddress(), getPortWithOffset()); serverSock.socket().bind(addr,getAcceptCount()); // 绑定到指定的服务地址和端口,这样你就可以通过这个访问服务(处理请求) } else { // Retrieve the channel provided by the OS Channel ic = System.inheritedChannel(); if (ic instanceof ServerSocketChannel) { serverSock = (ServerSocketChannel) ic; } if (serverSock == null) { throw new IllegalArgumentException(sm.getString("endpoint.init.bind.inherited")); } } serverSock.configureBlocking(true); //mimic APR behavior } Connector的启动
这里还是调用JMX模板方法startinternal方法, start方法的本质是委托给它protocolHandler调用其start方法进行处理 /** * Begin processing requests via this Connector. * * @exception LifecycleException if a fatal startup error occurs */ @Override protected void startInternal() throws LifecycleException { // Validate settings before starting if (getPortWithOffset() < 0) { throw new LifecycleException(sm.getString( "coyoteConnector.invalidPort", Integer.valueOf(getPortWithOffset()))); } setState(LifecycleState.STARTING); try { protocolHandler.start(); } catch (Exception e) { throw new LifecycleException( sm.getString("coyoteConnector.protocolHandlerStartFailed"), e); } }
protocolHandler.start()方法如下,它又交给endpoint进行start处理 @Override public void start() throws Exception { if (getLog().isInfoEnabled()) { getLog().info(sm.getString("abstractProtocolHandler.start", getName())); logPortOffset(); } // 本质是调用endpointstart方法 endpoint.start(); // 处理startasyncTimeout方法,启动异步线程,每60秒执行一次 monitorFuture = getUtilityExecutor().scheduleWithFixedDelay( new Runnable() { @Override public void run() { if (!isPaused()) { startAsyncTimeout(); } } }, 0, 60, TimeUnit.SECONDS); }
endpoint.start()就是调用startinternal方法。当然,它会先检查是否绑定端口,然后执行bindWithCleanup方法而不绑定。 public final void start() throws Exception { if (bindState == BindState.UNBOUND) { bindWithCleanup(); bindState = BindState.BOUND_ON_START; } startInternal(); }
让我们来看看NIOEndPointstartInternal方法做了啥 /** * Start the NIO endpoint, creating acceptor, poller threads. */ @Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; if (socketProperties.getProcessorCache() != 0) { processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, socketProperties.getProcessorCache()); } if (socketProperties.getEventCache() != 0) { eventCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, socketProperties.getEventCache()); } if (socketProperties.getBufferPool() != 0) { nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, socketProperties.getBufferPool()); } // 重点:创建Executor if (getExecutor() == null) { createExecutor(); } initializeConnectionLatch(); // Start poller thread poller = new Poller(); Thread pollerThread = new Thread(poller, getName() + "-ClientPoller"); pollerThread.setPriority(threadPriority); pollerThread.setDaemon(true); pollerThread.start(); startAcceptorThread(); } }
createExecutor()方法如下,本质是创建ThreadPolexecutor public void createExecutor() { internalExecutor = true; TaskQueue taskqueue = new TaskQueue(); TaskThreadFactory tf = new TaskThreadFactory(getName() + "-exec-", daemon, getThreadPriority()); executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), 60, TimeUnit.SECONDS,taskqueue, tf); taskqueue.setParent( (ThreadPoolExecutor) executor); }