有时候我们需要对我们的 springboot 应用配置 http,https 双协议,方式有很多,先记下一种:
我们先看 spring 官方文档对于此问题解决:
springboot 文档
78.7 Configure SSL
SSL can be configured declaratively by setting the various
server.ssl.*
properties, typically inapplication.properties
orapplication.yml
. The following example shows setting SSL properties inapplication.properties
:
server.port=8443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=secret
server.ssl.key-password=another-secret
See
Ssl
for details of all of the supported properties.
Using configuration such as the preceding example means the application no longer supports a plain HTTP connector at port 8080. Spring Boot does not support the configuration of both an HTTP connector and an HTTPS connector through
application.properties
. If you want to have both, you need to configure one of them programmatically. We recommend usingapplication.properties
to configure HTTPS, as the HTTP connector is the easier of the two to configure programmatically. See thespring-boot-sample-tomcat-multi-connectors
sample project for an example.
简单说就是 spingboot 启用 https 只需要在配置文件 application.properties 或 application.yml 当中配置 server.ssl.key 相关信息即可;但是 springboot 原生不支持 http,https 双协议同时启用,一旦启用 https,则 http 不可访问.由于 http 访问更容易通过编程实现因此一般在配置文件中配置 https,http 通过编程实现.
另附 http 实现代码如下:
@Configuration
public class EmbeddedHttpConfig {
@Value("${http.port}")
private int httpPort;
@Bean
public EmbeddedServletContainerCustomizer customizeTomcatConnector() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) container;
Connector connector = new Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL);
connector.setPort(httpPort);
containerFactory.addAdditionalTomcatConnectors(connector);
}
}
};
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于