import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
@Component
@Slf4j
public class NacosInstanceInfoUtils implements CommandLineRunner {
public static NacosDiscoveryProperties nacosDiscoveryProperties;
private NacosRegistration nacosRegistration;
public static String machineIp;
@Override
public void run(String... args) throws Exception {
log.info("getHostIp---------------------start-------------------------");
nacosRegistration = SpringJobBeanFactory.getBean(NacosRegistration.class);
Class cls1 = null;
try {
cls1 = Class.forName("com.alibaba.cloud.nacos.registry.NacosRegistration");
Field field = cls1.getDeclaredField("nacosDiscoveryProperties");
field.setAccessible(true);
Object nacosDiscoveryPropertiesValue = field.get(nacosRegistration);
this.nacosDiscoveryProperties = (NacosDiscoveryProperties) nacosDiscoveryPropertiesValue;
} catch (Exception e) {
e.printStackTrace();
log.error("nacos Listen for the event message,reflection method has a problem");
}
machineIp = nacosDiscoveryProperties.getIp();
log.info("getHostIp :{}--------------------end-------------------------",machineIp);
}
}
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringJobBeanFactory implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringJobBeanFactory.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
if (applicationContext == null){
return null;
}
return (T)applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> name) throws BeansException {
if (applicationContext == null){
return null;
}
return applicationContext.getBean(name);
}
}
|