我需要获取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
答案 0 :(得分:0)
传递端口号0是Java核心ServerSocket
类可以完成的技巧。 Undertow并不知道这一点。它只是假设端口始终是固定的。因此,没有正式的API可以读取实际使用的端口号。但是如果找到Undertow
对象,则可以执行以下操作:
// assuming you only have one:
ListenerInfo listenerInfo = undertow.getListenerInfo().iterator().next();
InetSocketAddress socketAddress = (InetSocketAddress) listenerInfo.getAddress();
URI uri = URI.create(listenerInfo.getProtcol() + "://" + socketAddress.getHostString() + ":" + socketAddress.getPort());
HTH