Java skill - 指定服务打开两个端口的顺序

Java skill - 指定服务打开两个端口的顺序

  • 添加ssl配置
  • 代码开启https端口
  • 讲解
  • 注意

继上一篇【Java skill - 服务同时开始https和http端口】,我们按照https、http的顺序打开端口,这篇我们就看看如何反过来,按照http、https的顺序打开端口。

添加ssl配置

在配置文件中添加配置

server:
  # http端口
  port: 7000

代码开启https端口

@Configuration
public class TomcatConfig {
    private String trustStorePassword = "123456";
    private String trustStore = "/opt/ops/cert/xes.p12";
    private String keyStorePassword = "123456";
    private String keyStore = "/opt/ops/cert/xes.p12";
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return factory -> {
            if (factory instanceof TomcatServletWebServerFactory) {
                // 创建和配置 SSLHostConfig 对象
                SSLHostConfig sslHostConfig = new SSLHostConfig();
                sslHostConfig.setTruststoreFile(trustStore);
                sslHostConfig.setTruststorePassword(trustStorePassword);
                sslHostConfig.setTruststoreType("PKCS12");
                sslHostConfig.setCertificateKeystoreFile(keyStore);
                sslHostConfig.setCertificateKeystorePassword(keyStorePassword);
                sslHostConfig.setCertificateKeystoreType("PKCS12");
                sslHostConfig.setCertificateVerification("true");
                TomcatServletWebServerFactory tomcat = (TomcatServletWebServerFactory) factory;
                Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
                connector.setAttribute("SSLEnabled", "true");
                // 添加 SSLHostConfig 到连接器
                connector.addSslHostConfig(sslHostConfig);
                connector.setScheme("https");
                connector.setSecure(true);
                connector.setPort(7001);
                tomcat.addAdditionalTomcatConnectors(connector);
            }
        };
    }
}

讲解

  1. 服务启动后,yml的ssl配置会执行并开启7000的http端口
  2. 然后,新加的配置类会执行并开启7001的https端口

注意

sslHostConfig.setCertificateVerification("true");

上面这句java代码一定要注意,如果不设置的话,https进来的请求头中是没有【javax.servlet.request.X509Certificate】证书信息的

你可能感兴趣的:(Java,skill,java,开发语言)