直接上代码工具类:
public class NacosTemplate {
private NamingService namingService;
public NacosTemplate() {
try {
Properties prop = System.getProperties();
String profile = (null != prop) ? prop.getProperty("spring.profiles.active") : AppConstant.DEV_CODE;
assert prop != null;
PropsUtil.setProperty(prop, "serverAddr", Constant.nacosAddr(profile));
PropsUtil.setProperty(prop, "namespace", Constant.nacosDataId(profile));
namingService = NacosFactory.createNamingService(prop);
} catch (NacosException e) {
e.printStackTrace();
}
}
public void registerNacosServer(Instance instance) throws Exception {
namingService.registerInstance(instance.getServiceName(), instance);
}
public void deleteNacosServer(Instance instance) throws Exception {
namingService.deregisterInstance(instance.getServiceName(), instance.getIp(), instance.getPort());
}
public List<Instance> discoverNacosServer(String serviceName) throws Exception {
return namingService.getAllInstances(serviceName);
}
}
开始手动注入
Instance instance = new Instance();
instance.setIp(this.serverNode.getIp());
instance.setPort(this.serverNode.getPort());
instance.setServiceName(super.getServerTioConfig().getName());
new NacosTemplate().registerNacosServer(instance);
log.debug(S"nacos注册成功呀");