Solon

如何增加 https 监听支持(ssl)

</> markdown

一般我们是使用 nginx (或者别的反向代理)添加 ssl 监听的。像:

server {
  listen        80;
  listen       443 ssl;
  server_name  solon.noear.org;  
  
  ssl_certificate   /data/_ca/solon.noear.org/solon.noear.org_chain.crt;
  ssl_certificate_key  /data/_ca/solon.noear.org/solon.noear.org_key.key;
  ssl_ciphers HIGH:!aNULL:!MD5;
  
  ssl_session_timeout 5m;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_prefer_server_ciphers on;
  
  location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
    proxy_pass http://127.0.0.1:8086;
  }
}

但某些情况下,我们可以无法使用反向代理,也或者不想用反向代理。这个时候需要我们的应用,直接监听 https 端口。

1、添加 ssl 证书配置

目前支持 ssl 证书配置的已适配 http server 适配有:

  • solon.boot.jdkhttp
  • solon.boot.jlhttp
  • solon.boot.smarthttp
  • solon.boot.jetty
  • solon.boot.undertow

请通过工具生成 ssl 证书,目前只支持:jkspfx 两种格式。配置示例:

server.port: 8081

server.ssl.keyStore: "/data/_ca/demo.jks" #或 "demo.pfx"
server.ssl.keyPassword: "demo"

以上配置启动后,正确打开为:https://localhost:8081

2、如果还想要有个 http 端口怎么办?(极少有需求会用到)

一个端口只能支持一种协议。配置 ssl 后,8081 端口便是 https 了。想要再有一个 http 端口,需要通过编码方式添加。

添加一个 8082 的 http 端口为例:(v2.2.18 后支持)

@SolonMain
public class SeverDemo {
    public static void main(String[] args) {
        Solon.start(SeverDemo.class, args, app -> {
            app.onEvent(HttpServerConfigure.class, e -> {
                //额外再添加一个 http 端口
                e.addHttpPort(8082);
            });
        });
    }
}

3、提醒

加上证书后,有些别的框架有可能也会读取证书。比如 mysql 链接器,注意 jdbcUrl 的 useSSL 控制。