修改application.yml配置
將原來的http改為https,application.yml配置文件中server添加相關的ssl配置
# Tomcat
server:
tomcat:
uri-encoding: UTF-8
max-threads: 1000
min-spare-threads: 30
port: 8443 #原來是http的8080
connection-timeout: 5000ms
servlet:
context-path: /
ssl: #添加的ssl自簽名證書
key-store: classpath:keystore.jks #注意路徑要配置正確
key-store-password: lovespring
key-alias: lovespring
key-password: lovespring
http: # 新加一個http的端口號配置
port: 8080
注意,如果ssl配置不正確,SpringApplication啟動后,會報端口號被占用,使用netstat -ano|findStr 8443一看,還真有兩個進程在使用tcp的8443端口 :(。其實是ssl配置不正確導致的,特地記錄一下。
修改Application代碼
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
// 如果要強制使用https,請松開以下注釋
// SecurityConstraint constraint = new SecurityConstraint();
// constraint.setUserConstraint("CONFIDENTIAL");
// SecurityCollection collection = new SecurityCollection();
// collection.addPattern("/*");
// constraint.addCollection(collection);
// context.addConstraint(constraint);
}
};
tomcat.addAdditionalTomcatConnectors(createStandardConnector()); // 添加http
return tomcat;
}
// 配置http
private Connector createStandardConnector() {
// 默認協(xié)議為org.apache.coyote.http11.Http11NioProtocol
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setSecure(false);
connector.setScheme("http");
connector.setPort(port);
connector.setRedirectPort(httpsPort); // 當http重定向到https時的https端口號
return connector;
}
@Value("${http.port}")
private Integer port;
@Value("${server.port}")
private Integer httpsPort;
注意,SpringBoot版本不一樣,代碼也不一樣,主要是TomcatServletWebServerFactory 這個類是2.0.x才有的。其它版本可以在官方示例鏈接中切換分支版本查看。