undertow服务器初始化

springboot整合undertow服务器的源码从老生常谈的createWebServer方法谈起。spring会在生成所有bean后到创建web容器,此时会到容器找到ServletWebServerFactory接口bean,spring会根据引入的框架确定生成的ServletWebServerFactory,我们在maven中引入了undertow后,由UndertowServletWebServerFactory实现。

	private void createWebServer() {WebServer webServer = this.webServer;ServletContext servletContext = getServletContext();if (webServer == null && servletContext == null) {ServletWebServerFactory factory = getWebServerFactory();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();}

UndertowServletWebServerFactory类的getWebServer会创建WebServer。

	public WebServer getWebServer(ServletContextInitializer... initializers) {Builder builder = this.delegate.createBuilder(this);DeploymentManager manager = createManager(initializers);return getUndertowWebServer(builder, manager, getPort());}

先用默认的配置构建Builder对象,再使用读取的配置。

Builder createBuilder(AbstractConfigurableWebServerFactory factory) {Ssl ssl = factory.getSsl();InetAddress address = factory.getAddress();int port = factory.getPort();Builder builder = Undertow.builder();if (this.bufferSize != null) {builder.setBufferSize(this.bufferSize);}if (this.ioThreads != null) {builder.setIoThreads(this.ioThreads);}if (this.workerThreads != null) {builder.setWorkerThreads(this.workerThreads);}if (this.directBuffers != null) {builder.setDirectBuffers(this.directBuffers);}if (ssl != null && ssl.isEnabled()) {new SslBuilderCustomizer(factory.getPort(), address, ssl, factory.getSslStoreProvider()).customize(builder);Http2 http2 = factory.getHttp2();if (http2 != null) {builder.setServerOption(UndertowOptions.ENABLE_HTTP2, http2.isEnabled());}}else {builder.addHttpListener(port, (address != null) ? address.getHostAddress() : "0.0.0.0");}builder.setServerOption(UndertowOptions.SHUTDOWN_TIMEOUT, 0);for (UndertowBuilderCustomizer customizer : this.builderCustomizers) {customizer.customize(builder);}return builder;}

之后再注册Servlet和Filter过滤器到容器中。

    public void deploy() {final DeploymentInfo deploymentInfo = originalDeployment.clone();if (deploymentInfo.getServletStackTraces() == ServletStackTraces.ALL) {UndertowServletLogger.REQUEST_LOGGER.servletStackTracesAll(deploymentInfo.getDeploymentName());}deploymentInfo.validate();final DeploymentImpl deployment = new DeploymentImpl(this, deploymentInfo, servletContainer);this.deployment = deployment;final ServletContextImpl servletContext = new ServletContextImpl(servletContainer, deployment);deployment.setServletContext(servletContext);handleExtensions(deploymentInfo, servletContext);final List<ThreadSetupHandler> setup = new ArrayList<>();setup.add(ServletRequestContextThreadSetupAction.INSTANCE);setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));setup.addAll(deploymentInfo.getThreadSetupActions());deployment.setThreadSetupActions(setup);deployment.getServletPaths().setWelcomePages(deploymentInfo.getWelcomePages());if (deploymentInfo.getDefaultEncoding() != null) {deployment.setDefaultCharset(Charset.forName(deploymentInfo.getDefaultEncoding()));}if(deploymentInfo.getDefaultRequestEncoding() != null) {deployment.setDefaultRequestCharset(Charset.forName(deploymentInfo.getDefaultRequestEncoding()));} else if (deploymentInfo.getDefaultEncoding() != null) {deployment.setDefaultRequestCharset(Charset.forName(deploymentInfo.getDefaultEncoding()));}if(deploymentInfo.getDefaultResponseEncoding() != null) {deployment.setDefaultResponseCharset(Charset.forName(deploymentInfo.getDefaultResponseEncoding()));} else if (deploymentInfo.getDefaultEncoding() != null) {deployment.setDefaultResponseCharset(Charset.forName(deploymentInfo.getDefaultEncoding()));}handleDeploymentSessionConfig(deploymentInfo, servletContext);deployment.setSessionManager(deploymentInfo.getSessionManagerFactory().createSessionManager(deployment));deployment.getSessionManager().setDefaultSessionTimeout(deploymentInfo.getDefaultSessionTimeout());try {deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Object>() {@Overridepublic Void call(HttpServerExchange exchange, Object ignore) throws Exception {final ApplicationListeners listeners = createListeners();listeners.start();deployment.setApplicationListeners(listeners);//now create the servlets and filters that we know about. We can still get more latercreateServletsAndFilters(deployment, deploymentInfo);//first initialize the temp dirinitializeTempDir(servletContext, deploymentInfo);//then run the SCI'sfor (final ServletContainerInitializerInfo sci : deploymentInfo.getServletContainerInitializers()) {final InstanceHandle<? extends ServletContainerInitializer> instance = sci.getInstanceFactory().createInstance();try {instance.getInstance().onStartup(sci.getHandlesTypes(), servletContext);} finally {instance.release();}}deployment.getSessionManager().registerSessionListener(new SessionListenerBridge(deployment, listeners, servletContext));for(SessionListener listener : deploymentInfo.getSessionListeners()) {deployment.getSessionManager().registerSessionListener(listener);}initializeErrorPages(deployment, deploymentInfo);initializeMimeMappings(deployment, deploymentInfo);listeners.contextInitialized();//runHttpHandler wrappedHandlers = ServletDispatchingHandler.INSTANCE;wrappedHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getInnerHandlerChainWrappers());wrappedHandlers = new RedirectDirHandler(wrappedHandlers, deployment.getServletPaths());if(!deploymentInfo.isSecurityDisabled()) {HttpHandler securityHandler = setupSecurityHandlers(wrappedHandlers);wrappedHandlers = new PredicateHandler(DispatcherTypePredicate.REQUEST, securityHandler, wrappedHandlers);}HttpHandler outerHandlers = wrapHandlers(wrappedHandlers, deploymentInfo.getOuterHandlerChainWrappers());wrappedHandlers = new PredicateHandler(DispatcherTypePredicate.REQUEST, outerHandlers, wrappedHandlers);wrappedHandlers = handleDevelopmentModePersistentSessions(wrappedHandlers, deploymentInfo, deployment.getSessionManager(), servletContext);MetricsCollector metrics = deploymentInfo.getMetricsCollector();if(metrics != null) {wrappedHandlers = new MetricsChainHandler(wrappedHandlers, metrics, deployment);}if( deploymentInfo.getCrawlerSessionManagerConfig() != null ) {wrappedHandlers = new CrawlerSessionManagerHandler(deploymentInfo.getCrawlerSessionManagerConfig(), wrappedHandlers);}final ServletInitialHandler servletInitialHandler = SecurityActions.createServletInitialHandler(deployment.getServletPaths(), wrappedHandlers, deployment, servletContext);HttpHandler initialHandler = wrapHandlers(servletInitialHandler, deployment.getDeploymentInfo().getInitialHandlerChainWrappers());initialHandler = new HttpContinueReadHandler(initialHandler);if(deploymentInfo.getUrlEncoding() != null) {initialHandler = Handlers.urlDecodingHandler(deploymentInfo.getUrlEncoding(), initialHandler);}deployment.setInitialHandler(initialHandler);deployment.setServletHandler(servletInitialHandler);deployment.getServletPaths().invalidate(); //make sure we have a fresh set of servlet pathsservletContext.initDone();return null;}}).call(null, null);} catch (Exception e) {throw new RuntimeException(e);}//any problems with the paths won't get detected until the data is initialize//so we force initialization heredeployment.getServletPaths().initData();for(ServletContextListener listener : deploymentInfo.getDeploymentCompleteListeners()) {listener.contextInitialized(new ServletContextEvent(servletContext));}state = State.DEPLOYED;}

WebServer接口的start()方法就会启动undertow服务器了,本质就是通过XNIO框架监听服务器端口号,接收请求并处理。处理请求时的io线程模型分数据处理线程和业务处理线程。

    public synchronized void start() {UndertowLogger.ROOT_LOGGER.infof("starting server: %s", Version.getFullVersionString());xnio = Xnio.getInstance(Undertow.class.getClassLoader());channels = new ArrayList<>();try {if (internalWorker) {worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, ioThreads).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, workerThreads).set(Options.WORKER_TASK_MAX_THREADS, workerThreads).set(Options.TCP_NODELAY, true).set(Options.CORK, true).addAll(workerOptions).getMap());}OptionMap socketOptions = OptionMap.builder().set(Options.WORKER_IO_THREADS, worker.getIoThreadCount()).set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true).set(Options.BALANCING_TOKENS, 1).set(Options.BALANCING_CONNECTIONS, 2).set(Options.BACKLOG, 1000).addAll(this.socketOptions).getMap();OptionMap serverOptions = OptionMap.builder().set(UndertowOptions.NO_REQUEST_TIMEOUT, 60 * 1000).addAll(this.serverOptions).getMap();ByteBufferPool buffers = this.byteBufferPool;if (buffers == null) {buffers = new DefaultByteBufferPool(directBuffers, bufferSize, -1, 4);}listenerInfo = new ArrayList<>();for (ListenerConfig listener : listeners) {UndertowLogger.ROOT_LOGGER.debugf("Configuring listener with protocol %s for interface %s and port %s", listener.type, listener.host, listener.port);final HttpHandler rootHandler = listener.rootHandler != null ? listener.rootHandler : this.rootHandler;OptionMap socketOptionsWithOverrides = OptionMap.builder().addAll(socketOptions).addAll(listener.overrideSocketOptions).getMap();......if (listener.type == ListenerType.HTTP) {HttpOpenListener openListener = new HttpOpenListener(buffers, undertowOptions);HttpHandler handler = rootHandler;if (http2) {handler = new Http2UpgradeHandler(handler);}openListener.setRootHandler(handler);final ChannelListener<StreamConnection> finalListener;if (listener.useProxyProtocol) {finalListener = new ProxyProtocolOpenListener(openListener, null, buffers, OptionMap.EMPTY);} else {finalListener = openListener;}ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(finalListener);AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), acceptListener, socketOptionsWithOverrides);server.resumeAccepts();channels.add(server);listenerInfo.add(new ListenerInfo("http", server.getLocalAddress(), openListener, null, server));} ......}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【数据结构】五分钟自测主干知识(十一)

上回&#xff08;半年前&#xff09;我们讲了二叉树&#xff0c;如果我们要找到二叉树某序遍历下的前驱和后继&#xff0c;我们需要对其作动态遍历求得&#xff0c;比较费时&#xff1b;或者给每个结点增加两个指针域prior和next&#xff0c;但比较费空间。 有没有既能省时间&…

docker部署SQL审核平台Archery

1、概述 Archery 是一个开源的 SQL 审核平台,专为数据库的 SQL 运维和管理而设计,广泛应用于企业的数据库运维工作中。其主要功能是帮助数据库管理员和开发人员实现 SQL 审核、SQL 执行、在线执行、查询、工单管理、权限控制等数据库管理相关的操作。 Archery 的主要功能包括…

网络地址转换——NAT技术详解

网络地址转换——NAT技术详解 一、引言 随着互联网的飞速发展&#xff0c;IP地址资源日益紧张。为了解决IP地址资源短缺的问题&#xff0c;NAT&#xff08;Network Address Translation&#xff0c;网络地址转换&#xff09;技术应运而生。NAT技术允许一个私有IP地址的网络通…

为什么我钟情于JPA:优雅数据访问的背后秘密

在Java开发的世界中&#xff0c;选择合适的数据访问框架不仅影响代码的可读性和维护性&#xff0c;更直接关系到项目的成败。虽然MyBatis及其衍生框架在灵活性和性能调优方面有其独特优势&#xff0c;但我更倾向于使用Java持久化API&#xff08;JPA&#xff09;。本文将探讨我为…

【K8S系列】Kubernetes Service 基础知识 详细介绍

在 Kubernetes 中&#xff0c;Service 是一种抽象的资源&#xff0c;用于定义一组 Pod 的访问策略。它为这些 Pod 提供了一个稳定的访问入口&#xff0c;解决了 Pod 可能频繁变化的问题。本文将详细介绍 Kubernetes Service 的类型、功能、使用场景、DNS 和负载均衡等方面。 1.…

Openlayers高级交互(2/20):清除所有图层的有效方法

Openlayers项目中,经常会放置很多的图层,在业务操作的时候,会做出删除所有图层的行为。这里面给出了一个详细的方法,能够有效的解决 清除所有图层的问题。 效果图 专栏名称内容介绍Openlayers基础实战 (72篇)专栏提供73篇文章,为小白群体提供基础知识及示例演示,能解决…

[软件工程]—桥接(Brige)模式与伪码推导

桥接&#xff08;Brige&#xff09;模式与伪码推导 1.基本概念 1.1 动机 由于某些类型的固有的实现逻辑&#xff0c;使它们具有两个变化的维度&#xff0c;乃至多个维度的变化。如何应对这种“多维度的变化”&#xff1f;如何利用面向对象技术是的类型可以轻松的沿着两个乃至…

022_matrix_dancing_in_Matlab中求解一个超简单的矩阵问题

矩阵体操 首先&#xff0c;可以复习一下向量、矩阵和索引的基础知识。 向量约定矩阵约定矩阵索引 一般而言&#xff0c;我们利用进行计算大概就是以下的步骤&#xff1a; #mermaid-svg-UovF0Uldf5XxntJi {font-family:"trebuchet ms",verdana,arial,sans-serif;fo…

MFC实现以不规则PNG图片作为窗口背景

效果图 显示的不规则PNG图片 头文件 #pragma once #include <gdiplus.h> #pragma comment (lib,"Gdiplus.lib")// CShowBack 对话框class CShowBack : public CDialogEx {DECLARE_DYNAMIC(CShowBack) public:CShowBack(CWnd* pParent nullptr); // 标准构…

C++学习路线(二十二)

构造函数 构造函数作用 在创建一个新的对象时&#xff0c;自动调用的函数&#xff0c;用来进行“初始化”工作:对这个对象内部的数据成员进行初始化。 构造函数特点 1.自动调用(在创建新对象时&#xff0c;自动调用) 2.构造函数的函数名&#xff0c;和类名相同 3.构造函数…

【002】调用kimi实现文件上传并进行分析_#py

调用kimi实现文件上传并进行分析 前言1. 上传文件并解析2. 调用方式3. 完整代码 前言 在【001】调用kimi实现AI对话_#py对Kimi有了一定的介绍&#xff0c;以及简单对话和连续对话的程序编写。 本次主要希望能通过kimi分析文件&#xff0c;总结文件的能力。 1. 上传文件并解析…

《近似线性可分支持向量机的原理推导》 目标函数 公式解析

本文是将文章《近似线性可分支持向量机的原理推导》中的公式单独拿出来做一个详细的解析&#xff0c;便于初学者更好的理解。 公式 9-38 解释&#xff1a; min ⁡ w , b , ξ 1 2 ∥ w ∥ 2 C ∑ i 1 N ξ i \min_{w, b, \xi} \quad \frac{1}{2} \|w\|^2 C \sum_{i1}^{N} \x…

httpd服务

文章目录 1、搭建一个网络yum源2、基于域名访问的虚拟主机3、基于端口来访问域名4、搭建个人网站5、加密访问显示自定义网页内容 1、搭建一个网络yum源 [roottest01 conf.d]# cat repo.conf <virtualhost *:80>documentroot /var/www/html/ServerName 10.104.43.154ali…

react18中的jsx 底层渲染机制相关原理

jsx 底层渲染机制 渲染 jsx 时&#xff0c;会先解析 jsx&#xff0c;生成一个虚拟 dom(virtual dom)。然后将虚拟 dom 渲染成真实 dom。如果 jsx 中包含事件&#xff0c;会将事件绑定到真实 dom 上。 虚拟 dom 对象&#xff0c;是框架内部构建的一套对象体系&#xff0c;对象…

常用环境部署(二十二)——MySQL的数据库迁移到另一个机器上

1、导出原数据库的数据 mysqldump -u [用户名] -p[密码] [数据库名] > database_dump.sql 命令示例&#xff1a; mysqldump -u root -p123456 wd > /opt/wd.sql 2、在新机器上创建数据库 mysql -u [用户名] -p -e "CREATE DATABASE [新数据库名]" 命令示…

无废话、光速上手 React-Router

React-Router React Router 是一个用于 React 应用的声明式路由库。它允许开发者通过组件化的方式定义应用的路由结构&#xff0c;使得路由管理更加直观和可维护 安装 pnpm i react-router-dom定义路由 定义路由有两种方式&#xff0c;分别是对象路由和路由组件&#xff0c…

k8s部署minio

k8s 部署minio 1.编辑yaml #编辑pvc cat > 01-minio-pvc.yaml <<EOF apiVersion: v1 kind: PersistentVolumeClaim metadata:name: minio-pvcnamespace: minio spec:accessModes:- ReadWriteManyresources:requests:storage: 10GistorageClassName: nfs-boge EOFcat …

AIGC时代 | 从零到一,打造你的专属AI Chat应用!

文章目录 目标功能概要&#xff08;1&#xff09;Chat 交互界面&#xff08;2&#xff09;流式接口&#xff08;3&#xff09;多轮会话&#xff08;4&#xff09;打字效果 系统架构&#xff08;1&#xff09;大模型服务层&#xff08;2&#xff09;应用服务层&#xff08;3&…

深入解析东芝TB62261FTG,步进电机驱动方案

TB62261FTG是一款由东芝推出的两相双极步进电机驱动器&#xff0c;采用了BiCD工艺&#xff0c;能够提供高效的电机控制。这款芯片具有多种优秀的功能&#xff0c;包括PWM斩波、内置电流调节、低导通电阻的MOSFET以及多种步进操作模式&#xff0c;使其非常适合用于需要精确运动控…

微信小程序的日期区间选择组件的封装和使用

组件化开发是一种将大型软件系统分解为更小、更易于管理和复用的独立模块或组件的方法。这种方法在现代软件开发中越来越受到重视&#xff0c;尤其是在前端开发领域。微信小程序的日期区间选择组件的使用 wxml 代码 <view><view bind:tap"chooseData">…