SpringBoot2.x 部署到阿里云(同时支持http,https)
1、背景
使得web应用能支持https,通常情况下有两种:一种是代理服务器把http转https, 另外一种是应用直接提供https服务。
1.1 代理服务器转换:
一般是使用nginx做web代理, 去下载nginx配套的证书,然后在nginx配置文件中,配置代理转发;
1.2 直接提供https:
使用应用本身的应用服务器开启https的服务。
2、场景
这里的场景是使用阿里云的SLB(负载均衡), 同时向外提供http和https服务。 阿里云的SLB只提供负载转发,并不提供协议转换(如果你高估阿里云SLB的话,这里就会是一个要踩的坑)。
3、springboot应用的证书选择和下载
我们的应用是使用SpringBoot2.x,并打包成jar。 springboot默认的使用tomcat作为内嵌服务的,所以我们的证书需要下载tomcat的证书。
下载的安装包里面有两个文件:xxx.pfx 和 pfx-password.txt。
其中将xxx.pfx 放在项目的根目录下。 发布的服务器的时候,直接和jar放在同一目录下。
4、springboot中的配置
4.1 application.yml
server:
port: 443
ssl:
key-store: open.pfx # 证书的路径
key-store-password: QWERTY # 证书密码
4.2 springboot启动类
package com.weipaiku;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.ResourceUtils;
@SpringBootApplication
@MapperScan("com.weipaiku.dao.mapper")
@EnableScheduling
public class APIApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(APIApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
//Connector监听的http的端口号
connector.setPort(80);
connector.setSecure(false);
//监听到http的端口号后转向到的https的端口号
connector.setRedirectPort(443);
return connector;
}
}
这样启动你就会发现console中,同时把80,443两个端口给启动起来了。
5、SLB挂在服务
51 创建SLB实例
5.2 添加监听端口
6.3 为SLB再添加证书
这里直接选择证书就可以了
到此全部完成!