一台机器可能存在多个网卡也就同时存在多个IP地址,如果我想知道我这个服务在向Nacos注册的时候使用的哪一个IP该怎么获取呢?
非常简单,你可以通过这种方式获取
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
public class NacosRegistrationRegister implements CommandLineRunner {
@Resource
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Override
public void run(String... args) throws Exception {
String ip = nacosDiscoveryProperties.getIp();
System.out.println(ip);
}
}
也可以在任意地方注入nacos的NacosDiscoveryProperties来获取比如下面
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@Configuration
public class NacosRegistrationRegister {
@Resource
private NacosDiscoveryProperties nacosDiscoveryProperties;
@PostConstruct
public void init() {
String ip = nacosDiscoveryProperties.getIp();
System.out.println(ip);
}
}
输出的就是本机向Nacos注册的IP地址
10.xxx.xxx.212