How to get local server host and port in Spring Boot?

后端 未结 9 1190
野性不改
野性不改 2020-12-09 02:27

I\'m starting up a Spring Boot application with mvn spring-boot:run.

One of my @Controllers needs information about the host and port the a

相关标签:
9条回答
  • 2020-12-09 03:14

    I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.

    You need to add the maven dependency first:

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>
    

    Then you can use the ApplicationInfoManager service in any of your Spring beans.

    @Autowired
    private ApplicationInfoManager applicationInfoManager;
    ...
    
    InstanceInfo applicationInfo = applicationInfoManager.getInfo();
    

    The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.

    0 讨论(0)
  • 2020-12-09 03:18

    IP Address

    You can get network interfaces with NetworkInterface.getNetworkInterfaces(), then the IP addresses off the NetworkInterface objects returned with .getInetAddresses(), then the string representation of those addresses with .getHostAddress().

    Port

    If you make a @Configuration class which implements ApplicationListener<EmbeddedServletContainerInitializedEvent>, you can override onApplicationEvent to get the port number once it's set.

    @Override
    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
        int port = event.getEmbeddedServletContainer().getPort();
    }
    
    0 讨论(0)
  • 2020-12-09 03:20

    You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar

    environment.getProperty("spring.cloud.client.ip-address");
    environment.getProperty("spring.cloud.client.hostname");
    

    spring.factories of spring-cloud-commons-2.1.0.RC2.jar

    org.springframework.boot.env.EnvironmentPostProcessor=\
    org.springframework.cloud.client.HostInfoEnvironmentPostProcessor
    
    0 讨论(0)
提交回复
热议问题