添加依赖
<dependency>
<!--web 模块-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!--排除tomcat依赖-->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- undertow -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
制作证书
使用JDK自带的keytool,证书类型为:PKCS12。
执行下面命令,输入证书口令,执行完命令后会在执行的文件夹生成一个keystore.p12的文件,将keystore.p12拷贝到src/main/resources下。
keytool -genkey -alias undertow -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -dname "CN=localhost, OU=localhost, O=localhost, L=Zhengzhou, ST=Henan, C=CN"
输入密钥库口令:
再次输入新口令:
application.yaml配置
server:
#HTTP2.0 HTTPS端口号
port: 8443
#自定义的HTTP1.1端口号
http1.1:
port: 8080
compression:
enabled: true
http2:
enabled: true
ssl:
enabled: true
key-store: classpath:keystore.p12
key-store-password: 123456
key-store-type: PKCS12
protocol: TLSv1.2
key-alias: undertow
undertow:
io-threads: 2
worker-threads: 36
buffer-size: 1024
directBuffers: true
添加HTTP支持
http2.0只支持https,如需同时使用http,则需添加下面配置
@Configuration
public class WebServerFactoryCustomizerConfig implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
@Value("${server.http1.1.port}")
private int httpPort;
/**
* 自定义HTTP端口号
*
* @param factory
*/
@Override
public void customize(UndertowServletWebServerFactory factory) {
factory.addBuilderCustomizers((UndertowBuilderCustomizer) builder -> {
builder.addHttpListener(httpPort, "0.0.0.0");
});
}
}
服务启动后可以在控制台看到如下信息:
测试验证
编写测试用的请求处理器,然后在浏览器分别输入https://localhost:8443/http/info 和 http://localhost:8080/http/info 进行验证。
@RestController
@RequestMapping("/http")
public class testController {
@RequestMapping(value = "/info")
public String info(HttpServletRequest request) {
return request.getProtocol();
}
}
参考文献
https://docs.spring.io/spring-boot/docs/2.0.5.RELEASE/reference/htmlsingle/#howto-configure-http2
https://blog.csdn.net/jaune161/article/details/82879044
https://www.bbsmax.com/A/KE5QX7v4JL/
https://www.jianshu.com/p/c171eed87f95