SpringBoot内嵌的Tomcat启动过程以及请求

1.springboot内嵌的tomcat的pom坐标

 启动后可以看到tomcat版本为9.0.46

 2.springboot 内嵌tomcat启动流程

点击进入SpringApplication.run()方法里面

看这次tomcat启动相关的核心代码refreshContext(context);刷新上下文方法

public ConfigurableApplicationContext run(String... args) {
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	ConfigurableApplicationContext context = null;
	configureHeadlessProperty();
	SpringApplicationRunListeners listeners = getRunListeners(args);
	listeners.starting();
	try {
		ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
		ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
		configureIgnoreBeanInfo(environment);
		Banner printedBanner = printBanner(environment);
		context = createApplicationContext();
		prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        // 此次的核心代码是刷新上下文方法
		refreshContext(context);
		afterRefresh(context, applicationArguments);
		stopWatch.stop();
		if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
		}
		listeners.started(context);
		callRunners(context, applicationArguments);
	}
	catch (Throwable ex) {
		handleRunFailure(context, ex, listeners);
		throw new IllegalStateException(ex);
	}

	try {
		listeners.running(context);
	}
	catch (Throwable ex) {
		handleRunFailure(context, ex, null);
		throw new IllegalStateException(ex);
	}
	return context;
}

进入 私有方法refreshContext

private void refreshContext(ConfigurableApplicationContext context) {
	if (this.registerShutdownHook) {
		try {
			context.registerShutdownHook();
		}
		catch (AccessControlException ex) {
			// Not allowed in some environments.
		}
	}
    // 核心方法,继续进入
	refresh((ApplicationContext) context);
}
@Deprecated
protected void refresh(ApplicationContext applicationContext) {
	Assert.isInstanceOf(ConfigurableApplicationContext.class, applicationContext);
    // 核心代码,继续进入方法
	refresh((ConfigurableApplicationContext) applicationContext);
}

进入refresh方法

protected void refresh(ConfigurableApplicationContext applicationContext) {
	// 核心方法,查看调用的方法refresh()
    applicationContext.refresh();
}

查看refresh方法,有三个实现类,进入默认的实现类ServletWebServerApplicationContext,定位到实现方法

@Override
public final void refresh() throws BeansException, IllegalStateException {
	try {
        // 进入父类refresh
		super.refresh();
	}
	catch (RuntimeException ex) {
		WebServer webServer = this.webServer;
		if (webServer != null) {
			webServer.stop();
		}
		throw ex;
	}
}

 看onRefresh()方法

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		prepareRefresh();
		// Tell the subclass to refresh the internal bean factory.
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		// Prepare the bean factory for use in this context.
		prepareBeanFactory(beanFactory);
		try {
			// Allows post-processing of the bean factory in context subclasses.
			postProcessBeanFactory(beanFactory);
			// Invoke factory processors registered as beans in the context.
			invokeBeanFactoryPostProcessors(beanFactory);
			// Register bean processors that intercept bean creation.
			registerBeanPostProcessors(beanFactory);
			// Initialize message source for this context.
			initMessageSource();
			// Initialize event multicaster for this context.
			initApplicationEventMulticaster();
            // 我们进入这个方法
			// Initialize other special beans in specific context subclasses.
			onRefresh();
			// Check for listener beans and register them.
			registerListeners();
			// Instantiate all remaining (non-lazy-init) singletons.
			finishBeanFactoryInitialization(beanFactory);
			// Last step: publish corresponding event.
			finishRefresh();
		}
		catch (BeansException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Exception encountered during context initialization - " +
						"cancelling refresh attempt: " + ex);
			}
			// Destroy already created singletons to avoid dangling resources.
			destroyBeans();
			// Reset 'active' flag.
			cancelRefresh(ex);
			// Propagate exception to caller.
			throw ex;
		}
		finally {
			// Reset common introspection caches in Spring's core, since we
			// might not ever need metadata for singleton beans anymore...
			resetCommonCaches();
		}
	}
}

 找到子类的实现方法:

@Override
protected void onRefresh() {
	super.onRefresh();
	try {
        // 核心代码,创建web服务器
		createWebServer();
	}
	catch (Throwable ex) {
		throw new ApplicationContextException("Unable to start web server", ex);
	}
}

进入createWebServer方法,ServletContext、WebServer在tomcat启动的时候一定为空,还没有初始化完成,会进入if代码块执行

private void createWebServer() {
	WebServer webServer = this.webServer;
    // tomcat启动servletContext才进行创建
	ServletContext servletContext = getServletContext();
	if (webServer == null && servletContext == null) {
		ServletWebServerFactory factory = getWebServerFactory();
        // 核心代码,通过工厂获取一个WebServer实例
		this.webServer = factory.getWebServer(getSelfInitializer());
		getBeanFactory().registerSingleton("webServerGracefulShutdown",
				new WebServerGracefulShutdownLifecycle(this.webServer));
		getBeanFactory().registerSingleton("webServerStartStop",
				new WebServerStartStopLifecycle(this, this.webServer));
	}
	else if (servletContext != null) {
		try {
			getSelfInitializer().onStartup(servletContext);
		}
		catch (ServletException ex) {
			throw new ApplicationContextException("Cannot initialize servlet context", ex);
		}
	}
	initPropertySources();
}

 getWebServer方法需要参数,该参数是一个方法getSelfInitializer(),找到

private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {
    // 方法引用,ServletContextInitializer是一个函数是接口,通过方法引用返回一个实现        
    // ServletContextInitializer的一个实现子类,作用同匿名内部类。
	return this::selfInitialize;
}

函数式接口:

@FunctionalInterface
public interface ServletContextInitializer {

	/**
	 * Configure the given {@link ServletContext} with any servlets, filters, listeners
	 * context-params and attributes necessary for initialization.
	 * @param servletContext the {@code ServletContext} to initialize
	 * @throws ServletException if any call against the given {@code ServletContext}
	 * throws a {@code ServletException}
	 */
	void onStartup(ServletContext servletContext) throws ServletException;

}

this::selfInitialize就是实例::方法名调用方式,this代表当前对象,selfInitialize是this(ServletWebServerApplicationContext)对象的一个私有方法

private void selfInitialize(ServletContext servletContext) throws ServletException {
	prepareWebApplicationContext(servletContext);
	registerApplicationScope(servletContext);
	WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);
	for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
		beans.onStartup(servletContext);
	}
}

继续进入getWebServer,发现是一个接口,有三个实现类Jetty、Tomcat、UnderTow,我们是Tomcat服务器,进入TomcatServletWebServerFactory中的实现方法

@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
	if (this.disableMBeanRegistry) {
		Registry.disableRegistry();
	}
	Tomcat tomcat = new Tomcat();
	File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
    // 用于设置临时文件的目录,这些目录用于存放JSP生成的源代码及Class文件x
	tomcat.setBaseDir(baseDir.getAbsolutePath());
	Connector connector = new Connector(this.protocol);
	connector.setThrowOnFailure(true);
	tomcat.getService().addConnector(connector);
	customizeConnector(connector);
    // 用于设置链接器,包括协议、I/0、端口、压缩、加密等等
	tomcat.setConnector(connector);
    // 是否自动部署
	tomcat.getHost().setAutoDeploy(false);
	configureEngine(tomcat.getEngine());
	for (Connector additionalConnector : this.additionalTomcatConnectors) {
		tomcat.getService().addConnector(additionalConnector);
	}
	prepareContext(tomcat.getHost(), initializers);
    // 核心代码
	return getTomcatWebServer(tomcat);
}
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
	return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown());
}

进入TomcatWebServer构造方法

public TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {
	Assert.notNull(tomcat, "Tomcat Server must not be null");
	this.tomcat = tomcat;
	this.autoStart = autoStart;
	this.gracefulShutdown = (shutdown == Shutdown.GRACEFUL) ? new GracefulShutdown(tomcat) : null;
    // 核心代码
	initialize();
}

 进入initialize()方法

private void initialize() throws WebServerException {
	logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));
	synchronized (this.monitor) {
		try {
			addInstanceIdToEngineName();

			Context context = findContext();
			context.addLifecycleListener((event) -> {
				if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {
					// Remove service connectors so that protocol binding doesn't
					// happen when the service is started.
					removeServiceConnectors();
				}
			});
            // 核心代码
			// Start the server to trigger initialization listeners
			this.tomcat.start();

			// We can re-throw failure exception directly in the main thread
			rethrowDeferredStartupExceptions();

			try {
				ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
			}
			catch (NamingException ex) {
				// Naming is not enabled. Continue
			}

			// Unlike Jetty, all Tomcat threads are daemon threads. We create a
			// blocking non-daemon to stop immediate shutdown
			startDaemonAwaitThread();
		}
		catch (Exception ex) {
			stopSilently();
			destroySilently();
			throw new WebServerException("Unable to start embedded Tomcat", ex);
		}
	}
}
public void start() throws LifecycleException {
	getServer();
    // 核心代码
	server.start();
}

进入start()方法,找到LifecycleBase实现类方法

 LifecycleBase类中init();startInternal();两个核心方法

 @Override
public final synchronized void start() throws LifecycleException {

	if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) ||
			LifecycleState.STARTED.equals(state)) {

		if (log.isDebugEnabled()) {
			Exception e = new LifecycleException();
			log.debug(sm.getString("lifecycleBase.alreadyStarted", toString()), e);
		} else if (log.isInfoEnabled()) {
			log.info(sm.getString("lifecycleBase.alreadyStarted", toString()));
		}

		return;
	}

	if (state.equals(LifecycleState.NEW)) {
        // 核心代码1
		init();
	} else if (state.equals(LifecycleState.FAILED)) {
		stop();
	} else if (!state.equals(LifecycleState.INITIALIZED) &&
			!state.equals(LifecycleState.STOPPED)) {
		invalidTransition(Lifecycle.BEFORE_START_EVENT);
	}

	try {
		setStateInternal(LifecycleState.STARTING_PREP, null, false);
        // 核心代码2
		startInternal();
		if (state.equals(LifecycleState.FAILED)) {
			// This is a 'controlled' failure. The component put itself into the
			// FAILED state so call stop() to complete the clean-up.
			stop();
		} else if (!state.equals(LifecycleState.STARTING)) {
			// Shouldn't be necessary but acts as a check that sub-classes are
			// doing what they are supposed to.
			invalidTransition(Lifecycle.AFTER_START_EVENT);
		} else {
			setStateInternal(LifecycleState.STARTED, null, false);
		}
	} catch (Throwable t) {
		// This is an 'uncontrolled' failure so put the component into the
		// FAILED state and throw an exception.
		handleSubClassException(t, "lifecycleBase.startFail", toString());
	}
}

 init()方法

 @Override
public final synchronized void init() throws LifecycleException {
	if (!state.equals(LifecycleState.NEW)) {
		invalidTransition(Lifecycle.BEFORE_INIT_EVENT);
	}

	try {
		setStateInternal(LifecycleState.INITIALIZING, null, false);
        // 核心代码
		initInternal();
		setStateInternal(LifecycleState.INITIALIZED, null, false);
	} catch (Throwable t) {
		handleSubClassException(t, "lifecycleBase.initFail", toString());
	}
}

initInternal有很多实现类,看组件Connector中的实现方法

 组件Connector类型方法

@Override
protected void initInternal() throws LifecycleException {

	super.initInternal();

	if (protocolHandler == null) {
		throw new LifecycleException(
				sm.getString("coyoteConnector.protocolHandlerInstantiationFailed"));
	}

	// Initialize adapter
	adapter = new CoyoteAdapter(this);
	protocolHandler.setAdapter(adapter);
	if (service != null) {
		protocolHandler.setUtilityExecutor(service.getServer().getUtilityExecutor());
	}

	// Make sure parseBodyMethodsSet has a default
	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) {
		AbstractHttp11JsseProtocol<?> jsseProtocolHandler =
				(AbstractHttp11JsseProtocol<?>) 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 {
		// 核心方法
		protocolHandler.init();
	} catch (Exception e) {
		throw new LifecycleException(
				sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e);
	}
}

进入实现类AbstractProtocol中init()方法

@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) {
		ObjectName rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName());
		this.rgOname = rgOname;
		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()方法

public final void init() throws Exception {
	if (bindOnInit) {
        // 核心代码
		bindWithCleanup();
		bindState = BindState.BOUND_ON_INIT;
	}
	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方法里面 

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;
	}
}
@Override
public void bind() throws Exception {
    // 核心代码
	initServerSocket();

	setStopLatch(new CountDownLatch(1));

	// Initialize SSL if needed
	initialiseSsl();

	selectorPool.open(getName());
}

初始化Socket 

protected void initServerSocket() throws Exception {
	if (getUseInheritedChannel()) {
		// 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"));
		}
	} else if (getUnixDomainSocketPath() != null) {
		SocketAddress sa = JreCompat.getInstance().getUnixDomainSocketAddress(getUnixDomainSocketPath());
		serverSock = JreCompat.getInstance().openUnixDomainServerSocketChannel();
		serverSock.bind(sa, getAcceptCount());
		if (getUnixDomainSocketPathPermissions() != null) {
			Path path = Paths.get(getUnixDomainSocketPath());
			Set<PosixFilePermission> permissions =
					PosixFilePermissions.fromString(getUnixDomainSocketPathPermissions());
			if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) {
				FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(permissions);
				Files.setAttribute(path, attrs.name(), attrs.value());
			} else {
				java.io.File file = path.toFile();
				if (permissions.contains(PosixFilePermission.OTHERS_READ) && !file.setReadable(true, false)) {
					log.warn(sm.getString("endpoint.nio.perms.readFail", file.getPath()));
				}
				if (permissions.contains(PosixFilePermission.OTHERS_WRITE) && !file.setWritable(true, false)) {
					log.warn(sm.getString("endpoint.nio.perms.writeFail", file.getPath()));
				}
			}
		}
	} else {
		serverSock = ServerSocketChannel.open();
		socketProperties.setProperties(serverSock.socket());
		InetSocketAddress addr = new InetSocketAddress(getAddress(), getPortWithOffset());
		serverSock.bind(addr, getAcceptCount());
	}
	serverSock.configureBlocking(true); //mimic APR behavior
}

startInternal();

看下这个方法,找到Connector里面的startInternal()方法实现

@Override
protected void startInternal() throws LifecycleException {

	// Validate settings before starting
	String id = (protocolHandler != null) ? protocolHandler.getId() : null;
	if (id == null && 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();方法里面。进入AbstractProtocol里面的实现方法

@Override
public void start() throws Exception {
	if (getLog().isInfoEnabled()) {
		getLog().info(sm.getString("abstractProtocolHandler.start", getName()));
		logPortOffset();
	}
    // 核心代码
	endpoint.start();
	monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(
			() -> {
				if (!isPaused()) {
					startAsyncTimeout();
				}
			}, 0, 60, TimeUnit.SECONDS);
}

找到endpoint.start()方法

public final void start() throws Exception {
	if (bindState == BindState.UNBOUND) {
		bindWithCleanup();
		bindState = BindState.BOUND_ON_START;
	}
    // 核心代码
	startInternal();
}

进入这个实现类里,找到实现方法

 

@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());
            }

            // Create worker collection
            if (getExecutor() == null) {
                createExecutor();
            }

            initializeConnectionLatch();

            // 核心代码 *******
            // Start poller thread
            poller = new Poller();
            Thread pollerThread = new Thread(poller, getName() + "-ClientPoller");
            // 设置进程的优先级
            pollerThread.setPriority(threadPriority);
            // 守护线程:当非守护线程销毁的时候,守护线程跟着销毁。当运行的唯一线程是守护线程时,        
            // Java虚拟机将退出
            pollerThread.setDaemon(true);
            // 开启线程
            pollerThread.start();

            startAcceptorThread();
        }
    }

Poller类是什么?

Poller里面的run方法

@Override
public void run() {
	// Loop until destroy() is called
    // 核心代码1 轮询
	while (true) {

		boolean hasEvents = false;

		try {
			if (!close) {
				hasEvents = events();
				if (wakeupCounter.getAndSet(-1) > 0) {
					// If we are here, means we have other stuff to do
					// Do a non blocking select
					keyCount = selector.selectNow();
				} else {
					keyCount = selector.select(selectorTimeout);
				}
				wakeupCounter.set(0);
			}
			if (close) {
				events();
				timeout(0, false);
				try {
					selector.close();
				} catch (IOException ioe) {
					log.error(sm.getString("endpoint.nio.selectorCloseFail"), ioe);
				}
				break;
			}
			// Either we timed out or we woke up, process events first
			if (keyCount == 0) {
				hasEvents = (hasEvents | events());
			}
		} catch (Throwable x) {
			ExceptionUtils.handleThrowable(x);
			log.error(sm.getString("endpoint.nio.selectorLoopError"), x);
			continue;
		}

		Iterator<SelectionKey> iterator =
			keyCount > 0 ? selector.selectedKeys().iterator() : null;
		// Walk through the collection of ready keys and dispatch
		// any active event.
		while (iterator != null && iterator.hasNext()) {
			SelectionKey sk = iterator.next();
			iterator.remove();
			NioSocketWrapper socketWrapper = (NioSocketWrapper) sk.attachment();
			// Attachment may be null if another thread has called
			// cancelledKey()
			if (socketWrapper != null) {
                // 核心代码2
				processKey(sk, socketWrapper);
			}
		}

		// Process timeouts
		timeout(keyCount,hasEvents);
	}

	getStopLatch().countDown();
}

启动一个Poller线程轮询监听NIO接收的请求,直到执行核心代码2processKey(sk, socketWrapper);Poller类会轮询监听Socket连接,到这里tomcat算启动成功啦。

springboot嵌入tomcat处理请求的过程

主要看下Poller类中的processKey方法,我们发起一个请求怎么处理的呢?

processKey方法

protected void processKey(SelectionKey sk, NioSocketWrapper socketWrapper) {
	try {
		if (close) {
			cancelledKey(sk, socketWrapper);
		} else if (sk.isValid() && socketWrapper != null) {
			if (sk.isReadable() || sk.isWritable()) {
				if (socketWrapper.getSendfileData() != null) {
					processSendfile(sk, socketWrapper, false);
				} else {
					unreg(sk, socketWrapper, sk.readyOps());
					boolean closeSocket = false;
					// Read goes before write
					if (sk.isReadable()) {
						if (socketWrapper.readOperation != null) {
                            // 核心代码
							if (!socketWrapper.readOperation.process()) {
								closeSocket = true;
							}
                        // 核心代码
						} else if (!processSocket(socketWrapper, SocketEvent.OPEN_READ, true)) {
							closeSocket = true;
						}
					}
					if (!closeSocket && sk.isWritable()) {
						if (socketWrapper.writeOperation != null) {
							if (!socketWrapper.writeOperation.process()) {
								closeSocket = true;
							}
						} else if (!processSocket(socketWrapper, SocketEvent.OPEN_WRITE, true)) {
							closeSocket = true;
						}
					}
					if (closeSocket) {
						cancelledKey(sk, socketWrapper);
					}
				}
			}
		} else {
			// Invalid key
			cancelledKey(sk, socketWrapper);
		}
	} catch (CancelledKeyException ckx) {
		cancelledKey(sk, socketWrapper);
	} catch (Throwable t) {
		ExceptionUtils.handleThrowable(t);
		log.error(sm.getString("endpoint.nio.keyProcessingError"), t);
	}
}

进入processSocket方法

public boolean processSocket(SocketWrapperBase<S> socketWrapper,
	SocketEvent event, boolean dispatch) {
	try {
		if (socketWrapper == null) {
			return false;
		}
        // 核心代码 线程
		SocketProcessorBase<S> sc = null;
		if (processorCache != null) {
			sc = processorCache.pop();
		}
		if (sc == null) {
			sc = createSocketProcessor(socketWrapper, event);
		} else {
			sc.reset(socketWrapper, event);
		}
        // 核心代码 获取线程池,通过线程池执行
		Executor executor = getExecutor();
		if (dispatch && executor != null) {
			executor.execute(sc);
		} else {
			sc.run();
		}
	} catch (RejectedExecutionException ree) {
		getLog().warn(sm.getString("endpoint.executor.fail", socketWrapper) , ree);
		return false;
	} catch (Throwable t) {
		ExceptionUtils.handleThrowable(t);
		// This means we got an OOM or similar creating a thread, or that
		// the pool and its queue are full
		getLog().error(sm.getString("endpoint.process.fail"), t);
		return false;
	}
	return true;
}

看看SocketProcessBase是什么?  实现了Runnable接口 

看下SocketProcessBase的run()方法

 @Override
    public final void run() {
        synchronized (socketWrapper) {
            // It is possible that processing may be triggered for read and
            // write at the same time. The sync above makes sure that processing
            // does not occur in parallel. The test below ensures that if the
            // first event to be processed results in the socket being closed,
            // the subsequent events are not processed.
            if (socketWrapper.isClosed()) {
                return;
            }
            // 核心代码
            doRun();
        }
    }

看下doRun()方法

找到过滤器链ApplicationFilterChain,找到doFilter()方法

@Override
public void doFilter(ServletRequest request, ServletResponse response)
	throws IOException, ServletException {

	if( Globals.IS_SECURITY_ENABLED ) {
		final ServletRequest req = request;
		final ServletResponse res = response;
		try {
			java.security.AccessController.doPrivileged(
					(java.security.PrivilegedExceptionAction<Void>) () -> {
                        // 核心代码
						internalDoFilter(req,res);
						return null;
					}
			);
		} catch( PrivilegedActionException pe) {
			Exception e = pe.getException();
			if (e instanceof ServletException)
				throw (ServletException) e;
			else if (e instanceof IOException)
				throw (IOException) e;
			else if (e instanceof RuntimeException)
				throw (RuntimeException) e;
			else
				throw new ServletException(e.getMessage(), e);
		}
	} else {
		internalDoFilter(request,response);
	}
}

定位到internalDoFilter()方法

private void internalDoFilter(ServletRequest request,
							  ServletResponse response)
	throws IOException, ServletException {

	// Call the next filter if there is one
	if (pos < n) {
		ApplicationFilterConfig filterConfig = filters[pos++];
		try {
			Filter filter = filterConfig.getFilter();

			if (request.isAsyncSupported() && "false".equalsIgnoreCase(
					filterConfig.getFilterDef().getAsyncSupported())) {
				request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
			}
			if( Globals.IS_SECURITY_ENABLED ) {
				final ServletRequest req = request;
				final ServletResponse res = response;
				Principal principal =
					((HttpServletRequest) req).getUserPrincipal();

				Object[] args = new Object[]{req, res, this};
				SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal);
			} else {
				filter.doFilter(request, response, this);
			}
		} catch (IOException | ServletException | RuntimeException e) {
			throw e;
		} catch (Throwable e) {
			e = ExceptionUtils.unwrapInvocationTargetException(e);
			ExceptionUtils.handleThrowable(e);
			throw new ServletException(sm.getString("filterChain.filter"), e);
		}
		return;
	}

	// We fell off the end of the chain -- call the servlet instance
	try {
		if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
			lastServicedRequest.set(request);
			lastServicedResponse.set(response);
		}

		if (request.isAsyncSupported() && !servletSupportsAsync) {
			request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,
					Boolean.FALSE);
		}
		// Use potentially wrapped request from this point
		if ((request instanceof HttpServletRequest) &&
				(response instanceof HttpServletResponse) &&
				Globals.IS_SECURITY_ENABLED ) {
			final ServletRequest req = request;
			final ServletResponse res = response;
			Principal principal =
				((HttpServletRequest) req).getUserPrincipal();
			Object[] args = new Object[]{req, res};
			SecurityUtil.doAsPrivilege("service",
									   servlet,
									   classTypeUsedInService,
									   args,
									   principal);
		} else {
            // 核心代码
			servlet.service(request, response);
		}
	} catch (IOException | ServletException | RuntimeException e) {
		throw e;
	} catch (Throwable e) {
		e = ExceptionUtils.unwrapInvocationTargetException(e);
		ExceptionUtils.handleThrowable(e);
		throw new ServletException(sm.getString("filterChain.servlet"), e);
	} finally {
		if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
			lastServicedRequest.set(null);
			lastServicedResponse.set(null);
		}
	}
}

定位到service()方法的实现类HttpServlet中的service()方法中

@Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException(lStrings.getString("http.non_http"));
        }
        // 核心代码
        service(request, response);
    }

继续进入到service()方法中

protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	long startTime = System.currentTimeMillis();
	Throwable failureCause = null;

	LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
	LocaleContext localeContext = buildLocaleContext(request);

	RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
	ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

	initContextHolders(request, localeContext, requestAttributes);

	try {
        // 核心代码
		doService(request, response);
	}
	catch (ServletException | IOException ex) {
		failureCause = ex;
		throw ex;
	}
	catch (Throwable ex) {
		failureCause = ex;
		throw new NestedServletException("Request processing failed", ex);
	}

	finally {
		resetContextHolders(request, previousLocaleContext, previousAttributes);
		if (requestAttributes != null) {
			requestAttributes.requestCompleted();
		}
		logResult(request, response, failureCause, asyncManager);
		publishRequestHandledEvent(request, response, startTime, failureCause);
	}
}

 进入doService()方法

 https://blog.csdn.net/z69183787/article/details/129240218
https://blog.csdn.net/sunshinezx8023/article/details/128630710

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/295524.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

银行卡号识别

导入库 from typing import Any, Union, Sequencefrom cv2.mat_wrapper import Mat from imutils import contours import numpy as np import argparse import imutils import cv2 import myutils设置参数 # 设置参数 from numpy import dtype, ndarray, genericap argpars…

“巴渝工匠杯”2022年重庆市职业院校技能大赛(高职组)云计算样题

“巴渝工匠杯”2022年重庆市职业院校技能大赛&#xff08;高职组&#xff09;云计算样题 需要软件包环境可私信博主 【赛程名称】云计算赛项第一场次-私有云 某企业拟使用OpenStack搭建一个企业云平台&#xff0c;以实现资源池化弹性管理、企业应用集中管理、统一安全认证和授…

Visual Studio 2022进行文件差异比较

前言 Visual Studio 2022在版本17.7.4中发布在解决方案资源管理器中比较文件的功能&#xff0c;通过使用此功能&#xff0c;可以轻松地查看两个文件之间的差异&#xff0c;包括添加、删除和修改的代码行。可以逐行查看差异&#xff0c;并根据需要手动调整和编辑文件内容以进行…

易图讯便携式三维电子沙盘实战应用系统

便携式三维电子沙盘采用军工加固三防高性能笔记本&#xff0c;具有IP65级防尘防水防摔性能&#xff0c;以大数据、云计算、虚拟现实、物联网、AI等先进技术为支撑&#xff0c;支持高清卫星影像、DEM高程数据、矢量数据、三维模型、倾斜摄像、BIM、点云、城市白模、等高线、标高…

数据结构学习 jz56数组中数字出现的次数

关键词&#xff1a;位运算 异或性质 虽然有两道题&#xff0c;但是其实应该分成三个级别的题目。 题目一&#xff1a; 一个整型数组 sockets 里除 一个 数字之外&#xff0c;其他数字都出现了两次。 思路&#xff1a;异或的性质 复杂度计算&#xff1a; 时间复杂度O(n) 空…

在Go语言中处理HTTP请求中的Cookie

在Web开发中&#xff0c;Cookie是一种常用的技术&#xff0c;用于在客户端存储数据&#xff0c;并在随后的请求中发送回服务器。Go语言的标准库提供了强大的支持来处理HTTP请求中的Cookie。 首先&#xff0c;让我们了解如何在Go语言中设置Cookie。以下是一个简单的示例&#x…

three.js场景设计器-小地图的视角参考功能

three.js实现场景方向的左上角小地图 思路 1&#xff1a;创建单独场景 2.添加辅助线 3.添加坐标轴的XYZ文字-使用sprite实现 4.旋转主视图时同步相机位置到小地图。 <template> <div ref"miniMapContainer" class"mini-map"></div>…

Apache Commons Email在邮件发送中的应用

第1章&#xff1a;简介 大家好&#xff0c;我是小黑&#xff0c;今天咱们聊聊Apache Commons Email这个库&#xff0c;它在发送邮件方面可谓是小而美的利器。Apache Commons Email基于JavaMail API&#xff0c;但它提供了更简洁、更易用的接口&#xff0c;让咱们在处理电子邮件…

如果PostgreSQL有两层nginx代理,会发生什么事?

转载说明&#xff1a;如果您喜欢这篇文章并打算转载它&#xff0c;请私信作者取得授权。感谢您喜爱本文&#xff0c;请文明转载&#xff0c;谢谢。 1. 前言 PostgreSQL默认只能本机连接&#xff0c;若要在别的客户端远程连接pgsql&#xff0c;则需要修改配置文件pg_hba.conf&a…

CommonJS 和 ES6 Module:一场模块规范的对决(下)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

QML —— SwipeView、PageIndicator组合示例(附完整源码)

示例效果 介绍 SwipeView提供了一个基于滑动的导航模型,由一组页面组成。一次只能看到一个页面。用户可以通过横向滑动在页面之间导航。请注意,SwipeView本身是完全不可见的。建议将其与PageIndicator结合使用,以向用户提供有多个页面的视觉线索。 PageIndicator用于指示包含…

UG装配-沿线运动

如果希望图中圆柱销沿着槽运动&#xff0c;直接约束面是困难的&#xff0c;我们可以画出圆弧的中心线和圆柱销的中心点&#xff0c;约束点在线上&#xff0c;进行移动 需要注意的是&#xff0c;我们在零件中画点和线的时候&#xff0c;在装配体默认加载模型引用集的时候是无法显…

生活中的物理3——神奇陷阱(随机倒下的抽屉柜门)

1实验 材料&#xff1a;大自然&#xff08;风&#xff09;、抽屉门松掉的抽屉 实验 1、找一个大风的日子&#xff0c;打开窗户&#xff08;不要找下雨天&#xff0c;不然你会被你亲爱的嫲嫲KO&#xff09; 2、让风在抽屉面前刮过 3、你发现了什么&#xff1f;&#xff1f;&…

南某人:从工厂到品牌的华丽转身!

南某人&#xff0c;这个名字在中国的市场上已经响当当&#xff0c;但你知道吗&#xff1f;这个品牌其实并没有自己的工厂和门店。那么&#xff0c;他们是如何做到年收入高达40亿的呢&#xff1f; 起初&#xff0c;南某人和许多中国品牌一样&#xff0c;从生产保暖内衣起家。然…

傅里叶级数、傅里叶变换、小波变换、离散余弦变换的理解

目录 1. 傅里叶级数2.傅里叶变换 1. 傅里叶级数 功能&#xff1a;能把任意周期性函数展开成一系列正弦、余弦函数的和。 公式&#xff1a; f ( x ) a 0 2 ∑ n 1 ∞ ( a n cos ⁡ ( 2 π n x T ) b n sin ⁡ ( 2 π n x T ) ) 傅里叶系数 a n 2 T ∫ x 0 x 0 T f ( x )…

机器学习(三) -- 特征工程(1)

系列文章目录 机器学习&#xff08;一&#xff09; -- 概述 机器学习&#xff08;二&#xff09; -- 数据预处理&#xff08;1-3&#xff09; 机器学习&#xff08;三&#xff09; -- 特征工程&#xff08;1-2&#xff09; 未完待续…… 目录 系列文章目录 前言 一、特征…

nginx 一、安装与conf浅析

文章目录 一、安装nginxdocker方式安装linux方式安装Ubuntu 或 Debian 系统&#xff1a;CentOS 或 RHEL 系统&#xff1a; macOS 系统&#xff08;使用 Homebrew&#xff09;&#xff1a;Windows 系统&#xff1a; 二、nginx.conf浅析 Nginx&#xff08;发音为“engine-x”&…

服务器CentOs8 安装RocketMQ 4.9.4

前置条件 安装好java环境 下载、上传、解压 下载二进制包 传送门 上传到服务器&#xff0c;这里上传到了/usr/local目录下 解压&#xff1a; unzip rocketmq-all-4.9.4-bin-release.zip移动到新的文件夹 mv /rocketmq-all-4.9.4-bin-release /rocketmq修改配置 修改conf下…

第 378 场 LeetCode 周赛题解

A 检查按位或是否存在尾随零 枚举&#xff1a;枚举两个元素的组合即可 class Solution { public:bool hasTrailingZeros(vector<int> &nums) {int n nums.size();for (int i 0; i < n; i)for (int j 0; j < i; j)if ((nums[i] | nums[j]) % 2 0)return tru…

Python从入门到精通总结规划

Python从入门到精通专栏&#xff1a;http://t.csdnimg.cn/4Lals 时光飞逝&#xff0c;转眼间我们的Python从入门到精通专栏已经接近尾声。 在这里&#xff0c;向大家表示最诚挚的感谢。感谢你们一直以来对Python学习的热情&#xff0c;以及对本专栏的持续关注和支持。 回顾过去…