gateway 支持同时使用 https 和 http访问

发布于:2024-11-23 ⋅ 阅读:(16) ⋅ 点赞:(0)
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.HttpHandler;

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

@Configuration
@ConditionalOnProperty(name = "server.ssl.enabled", havingValue = "true", matchIfMissing = true)
public class HttpsConfiguration {

    @Value("${server.http.port:7081}")
    private Integer httpPort;

    // 此处注释的代码在gateway 不生效,在其他模块是可以同时启动 https 和 http 访问的
    /*@Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(httpConnector()); // ???不起作用, 没有监听到 httpPort 端口
        return tomcat;
    }

    private Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        return connector;
    }*/

    @Autowired
    private HttpHandler httpHandler;

    private WebServer webServer;

    @PostConstruct
    public void start(){
        NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory(httpPort);
        webServer = factory.getWebServer(httpHandler);
        webServer.start();
    }

    @PreDestroy
    public void stop(){
        webServer.stop();
    }
}

参考:https://blog.csdn.net/siqiangming/article/details/130283755


网站公告

今日签到

点亮在社区的每一天
去签到