优秀的编程知识分享平台

网站首页 > 技术文章 正文

springboot 2.* 嵌入式 servlet Web 容器

nanyue 2024-09-23 10:36:33 技术文章 4 ℃

嵌入式与普通部署区别

最早期的web 服务,将打好的war包放在web容器的目录下,如Tomcat 是放在webapps.但spring boot 的嵌入式,是通过

ServletWebServerApplicationContext,注册上下文,引导 tomcat 启动。

tomcat

spring boot web 依赖默认依赖 tomcat。

tomcat 配置. 实现 https,http 方式

生成密钥的方式

 keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650

实现实例

public class CustomServletContainer implements 实现WebServerFactoryCustomizer <configurablewebserverfactory> {
 /**~~~~
 *
 * @param factory
 */
 @Override
 public void customize(ConfigurableWebServerFactory factory) {
 factory.setPort(8082);
 }
 @Bean
 public ServletWebServerFactory servletContainer() {
 TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
 tomcat.addAdditionalTomcatConnectors(createStandardConnector());
 return tomcat;
 }
 
 private Connector createSslConnector() {
 Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
 Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
 try {
 File keystore = new ClassPathResource("keystore.p12").getFile();
 File truststore = new ClassPathResource("keystore.p12").getFile();
 connector.setScheme("https");
 connector.setSecure(true);
 connector.setPort(8443);
 protocol.setSSLEnabled(true);
 protocol.setKeystoreFile(keystore.getAbsolutePath());
 protocol.setKeystorePass("123456");
 protocol.setKeystoreType("PKCS12");
// protocol.setTruststoreFile(truststore.getAbsolutePath());
 //// protocol.setTruststorePass("password");
 protocol.setKeyAlias("tomcat");
 return connector;
 }
 catch (IOException ex) {
 throw new IllegalStateException("can't access keystore: [" + "keystore"
 + "] or truststore: [" + "keystore" + "]", ex);
 }
 }
}

jetty

在web 中排除 tomcat

 <dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-web</artifactid>
 <exclusions>
 <!-- Exclude the Tomcat dependency -->
 <exclusion>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-tomcat</artifactid>
 </exclusion>
 </exclusions>
 </dependency>
 <dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-jetty</artifactid>
 </dependency>

undertow

如果undertow这个名称不熟悉,则JBoss 应该大名鼎鼎。使用方式同上

 <dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-web</artifactid>
 <exclusions>
 <!-- Exclude the Tomcat dependency -->
 <exclusion>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-tomcat</artifactid>
 </exclusion>
 </exclusions>
 </dependency>
 <dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-undertow</artifactid>
 </dependency>

总结

spring boot 针对 servlet web 容器,提供 jetty,undertow,tomcat支持。下面会整理 响应式web 容器的支持。在servlet 3.1中 有个重大的功能,支持 异步请求。在此基础上,Spring 5 最大的改进也是提供了 响应式编程(reactive web),很有意思.

源代码

如有帮助,关注下吆。

Tags:

最近发表
标签列表