使Spring Boot同时支持HTTP和HTTPS的方式

先在application.properties配置如下信息,使其支持https

#https的端口
server.port=8443
#证书
server.ssl.key-store=classpath:test.jks
server.ssl.key-store-password=test
server.ssl.keyStoreType=jks
#指定密钥内容,不然chrome浏览器无法访问
server.ssl.ciphers=TLS_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,SSL_RSA_WITH_3DES_EDE_CBC_SHA,TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
#http的端口
http.port=8090
新增HttpsConfig文件
package com.ms.biz.api.config;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class HttpsConfig {

	@Autowired
	private Environment env;
	
	@Bean
	public EmbeddedServletContainerFactory servletContainer() {
		TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
		tomcat.addAdditionalTomcatConnectors(createHttpConnector());
		return tomcat;
	}

	private Connector createHttpConnector() {
		Integer port = Integer.valueOf(env.getProperty("http.port"));
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setScheme("http");
		connector.setPort(port);
		connector.setSecure(false);
		return connector;
	}
}
然后启动服务,即可看到同时有https的8443和http8090端口启动
评论 (0)