How to get a software port programmatically in Dropwizard

I am using dropwizard version 0.7.1. It is configured to use a "random" (ephemeral) port (server.applicationConnectors.port = 0). I want to get which port is actually used after startup, but I can not find any information on how to do this.

+6
source share
2 answers

You can get the serverStarted from the lifecycle listener to figure this out.

 @Override public void run(ExampleConfiguration configuration, Environment environment) throws Exception { environment.lifecycle().addServerLifecycleListener(new ServerLifecycleListener() { @Override public void serverStarted(Server server) { for (Connector connector : server.getConnectors()) { if (connector instanceof ServerConnector) { ServerConnector serverConnector = (ServerConnector) connector; System.out.println(serverConnector.getName() + " " + serverConnector.getLocalPort()); // Do something useful with serverConnector.getLocalPort() } } } }); } 
+6
source

I find this approach worked well for me with the Simple and Default server configurations in Dropwizard.

 public void run(ExampleConfiguration configuration, Environment environment) throws Exception { Stream<ConnectorFactory> connectors = configuration.getServerFactory() instanceof DefaultServerFactory ? ((DefaultServerFactory)configuration.getServerFactory()).getApplicationConnectors().stream() : Stream.of((SimpleServerFactory)configuration.getServerFactory()).map(SimpleServerFactory::getConnector); int port = connectors.filter(connector -> connector.getClass().isAssignableFrom(HttpConnectorFactory.class)) .map(connector -> (HttpConnectorFactory) connector) .mapToInt(HttpConnectorFactory::getPort) .findFirst(); .orElseThrow(IllegalStateException::new); } 
+1
source

Source: https://habr.com/ru/post/974457/


All Articles