public class NacosConfigClient {
public static void main(String[] args) {
// Nacos 配置中心的服务地址
String serverAddr = "localhost:8848";
// 配置中心的命名空间,如果没有可以留空
String namespace = "";
// 要获取的配置的 Data ID
String dataId = "xxxxx.yml";
// 配置的分组
String group = "DEFAULT_GROUP";
// 创建 Nacos 配置服务
ConfigService configService = createConfigService(serverAddr, namespace);
// 获取配置
String config = getConfig(configService, dataId, group);
System.out.println("配置内容:" + config);
}
private static ConfigService createConfigService(String serverAddr, String namespace) {
try {
Properties properties = new Properties();
properties.setProperty("serverAddr", serverAddr);
if (namespace != null && !namespace.isEmpty()) {
properties.setProperty("namespace", namespace);
}
return new NacosConfigService(properties);
} catch (NacosException e) {
e.printStackTrace();
return null;
}
}
private static String getConfig(ConfigService configService, String dataId, String group) {
try {
return configService.getConfig(dataId, group, 3000);
} catch (NacosException e) {
e.printStackTrace();
return null;
}
}
}