如何设置Spring Boot以运行HTTPS / HTTP端口

2022-08-31 17:28:08

Spring boot具有一些属性来配置Web端口和SSL设置,但是一旦设置了SSL证书,http端口就会变成https端口。

那么,我如何保持两个端口在其上运行,例如:80和443同时运行?

如您所见,只有一个端口的属性,在本例中为“server.ssl”被启用,这使得http端口自动禁用。

##############
### Server ###
##############
server.port=9043
server.session-timeout=1800
server.ssl.key-store=file:///C:/Temp/config/localhost.jks
server.ssl.key-store-password=localhost
server.ssl.key-password=localhost
server.ssl.trust-store=file:///C:/Temp/config/localhost.jks
server.ssl.trust-store-password=localhost

我甚至试图使用Tomcat或Undertow。我将不胜感激任何帮助!


答案 1

使用属性的 Spring Boot 配置只允许配置一个连接器。您需要的是多个连接器,为此,您必须编写一个配置类。按照中的说明进行操作

https://docs.spring.io/spring-boot/docs/1.2.3.RELEASE/reference/html/howto-embedded-servlet-containers.html

您可以在下面找到一个通过属性配置HTTPS的工作示例,然后通过嵌入式ServletContainerCustomizer配置HTTP

http://izeye.blogspot.com/2015/01/configure-http-and-https-in-spring-boot.html?showComment=1461632100718#c4988529876932015554

server:
  port: 8080
  ssl:
    enabled: true
    keyStoreType: PKCS12
    key-store: /path/to/keystore.p12
    key-store-password: password
  http:
    port: 8079

@Configuration
public class TomcatConfig {

@Value("${server.http.port}")
private int httpPort;

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    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);
            }
        }
    };
}
}

答案 2

目前接受的答案工作完美,但如果您希望它与Spring Boot及更高版本配合使用,则需要进行一些调整:2.0.0

@Component
public class HttpServer {
  @Bean
  public ServletWebServerFactory servletContainer(@Value("${server.http.port}") int httpPort) {
      Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
      connector.setPort(httpPort);

      TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
      tomcat.addAdditionalTomcatConnectors(connector);
      return tomcat;
  }
}

Kotlin 版本

@Component
class HttpServer {
  @Bean
  fun servletContainer(@Value("\${server.http.port}") httpPort: Int): ServletWebServerFactory {
    val connector = Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL)
    connector.setPort(httpPort)

    val tomcat = TomcatServletWebServerFactory()
    tomcat.addAdditionalTomcatConnectors(connector)
    return tomcat
  }
}