当前位置: 首页>后端>正文

Srping Gateway同时支持http和https

1. 环境信息

  • java 1.8
  • SpringBoot 2.4.4
  • SpringGateway 3.0.5

2. 配置application.properties

证书生成方法,参考《使用keytool生成SSL证书》

... 省略
# 启用https之后,这是https的端口。server-port来自System.setProperty("Server-port" , "12345")
server.port=${server-port} 
# https
server.ssl.enabled=true
server.ssl.key-alias=gateway
server.ssl.key-store-password=Tpcloud@321
# 把证书放在应用的配置目录下,不打包到Jar里面。System.setProperty("app.dir.config" , "应用配置目录")
server.ssl.key-store=${app.dir.config}/gateway.pfx
server.ssl.key-store-type=PKCS12
#
spring.cloud.gateway.httpclient.ssl.useInsecureTrustManager=true
spring.cloud.gateway.httpclient.ssl.handshake-timeout-millis=10000
spring.cloud.gateway.httpclient.ssl.close-notify-flush-timeout-millis=3000
spring.cloud.gateway.httpclient.ssl.close-notify-read-timeout-millis= 0
... 省略

3. 支持上Http服务。

需要确保下面这个类能被Spring扫描到。

package com.xxxx.xxxx.ms.gateway.componet;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.stereotype.Component;

@Component
public class HttpServer
{
    @Value("${http-port}")
    int mPort ;
    
    @Autowired
    HttpHandler mHttpHandler ;
    
    WebServer mWebServer ;
    
    public HttpServer()
    {
    }
    
    @PostConstruct
    void _init()
    {
        NettyReactiveWebServerFactory fac = new NettyReactiveWebServerFactory(mPort) ;
        mWebServer = fac.getWebServer(mHttpHandler) ;
        mWebServer.start(); 
    }
    
    @PreDestroy
    public void stop()
    {
        mWebServer.stop() ;
    }
}


https://www.xamrdz.com/backend/39u1936037.html

相关文章: