How to configure in Spring Boot 2 (w/ WebFlux) two ports for HTTP and HTTPS?

不问归期 提交于 2020-01-03 15:33:23

问题


Can anybody tell me how 2 ports (for HTTP and HTTPS) can be configured when using Spring Boot 2 and WebFlux? Any hint is appreciated!


回答1:


This isn't directly supported by Spring Boot 2 yet.

But, you may be able to get it to work in a couple of ways.

By default, Spring Boot WebFlux uses Netty. If you are already configured for ssl, then Spring Boot will start up and open port 8443 (or whatever you have configured).

Then, to add 8080, you can do:

@Autowired
HttpHandler httpHandler;

WebServer http;

@PostConstruct
public void start() {
    ReactiveWebServerFactory factory = new NettyReactiveWebServerFactory(8080);
    this.http = factory.getWebServer(this.httpHandler);
    this.http.start();
}

@PreDestroy
public void stop() {
    this.http.stop();
}

Which is a bit clunky since your https configuration is in one spot (application.yml) and your http configuration is in Java config, but I have tested this myself with a toy application. Not sure how robust of a solution it is, though.

Another option that may work is to try the equivalent of other suggestions, but use the reactive version of the class, which is TomcatReactiveWebServerFactory. I'm not aware of any way to provide more than one connector for it, but you could possibly override its getWebServer method:

@Bean
TomcatReactiveWebServerFactory twoPorts() {
    return new TomcatReactiveWebServerFactory(8443) {
        @Override
        public WebServer getWebServer(HttpHandler httpHandler) {
           // .. copy lines from parent class
           // .. and add your own Connector, similar to how tutorials describe for servlet-based support
        }
    }
}

Also, a bit messy, and I have not tried that approach myself.

Of course, keep track of the ticket so you know when Spring Boot 2 provides official support.




回答2:


Follow the instructions listed in the link provided by jojo_berlin (here's the link). Instead of using his EmbeddedTomcatConfiguration class though, use this below

@Configuration
public class TomcatConfig {

    @Value("${server.http.port}")
    private int httpPort;

    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setPort(httpPort);
        factory.addAdditionalTomcatConnectors(connector);

        return factory;
    }
}



回答3:


Actually you can define a second connector as described here . So you can define a https connector as your default and an additional HTTP Connector



来源:https://stackoverflow.com/questions/48221194/how-to-configure-in-spring-boot-2-w-webflux-two-ports-for-http-and-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!