2014-08-28 64 views

回答

5

您可以從生命週期偵聽器獲取serverStarted回調來解決這個問題。

@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() 
     } 
     } 
    } 
    }); 
} 
0

我發現這種方法在Dropwizard中同時適用於Simple和Default服務器配置。

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); 
} 
相關問題