当server.port为0时无法获取随机端口>>

问题描述 投票:1回答:1

我需要获取由Sprint引导应用启动了underwow的端口号。我在application.properties中定义了server.port = 0。我不能使用像8080这样的固定端口号。

package com.aggregate.application;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;


@Configuration
@ComponentScan(basePackages = {"com.aggregate"})
@EnableAutoConfiguration
public class GServiceApplication extends SpringBootServletInitializer 
    implements ApplicationListener<ApplicationReadyEvent> {

        @Autowired
        private ApplicationContext applicationContext;


        @Override
        public void onApplicationEvent(ApplicationReadyEvent event) {
            try {
                String ip = InetAddress.getLocalHost().getHostAddress();
                String port = applicationContext.getBean(Environment.class).getProperty("server.port");
               System.out.printf("ip:port=" +ip+ ":"+port);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
     public static void main(String[] args) throws UnknownHostException 
     {

            SpringApplication application = new SpringApplication(GServiceApplication.class);
            Properties properties = new Properties();
            properties.put("server.port", 0);
            properties.put("server.address", InetAddress.getLocalHost().getHostAddress());
            application.setDefaultProperties(properties);
            application.run(args);

     }

}

[Undertow启动:-o.s.b.w.e.u.UndertowServletWebServer:Undertow在端口55646(http)上启动,上下文路径为”,如控制台中所示]

预期结果:-ip:port = xx.xx.x.1x1:55646实际结果:-ip:port = xx.xx.x.1x1:0

我需要获取由Sprint引导应用启动了underwow的端口号。我在application.properties中定义了server.port = 0。我不能使用像8080这样的修复端口号。package com.aggregate ....

spring-boot undertow
1个回答
0
投票

传递端口号0是Java核心ServerSocket类可以完成的技巧。 Undertow并不知道这一点。它只是假设端口始终是固定的。因此,没有正式的API可以读取实际使用的端口号。但是,如果找到Undertow对象,则可以执行以下操作:

© www.soinside.com 2019 - 2024. All rights reserved.