Nacos提供配置订阅者即监听者查询的能力,同时提供客户端当前配置的MD5校验值,以便帮助用户更好地检查配置变更是否推送到Client端
1.编写监听代码
package com.leo.nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import java.util.Properties;
import java.util.concurrent.Executor;
public class SimpleDemoMain {
public static void main(String[] args) throws NacosException, InterruptedException {
// 使用nacos client 远程获取nacos服务上的配置信息
// nacos 地址
String serverAddr = "127.0.0.1:8848";
// Data Id
String dataId = "nacos-simple-demo.yaml";
// Group
String group = "DEFAULT_GROUP";
// Namespace
String namespace = "0c74cab7-f503-4fa8-af6d-25a5b65f598c";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
properties.put("namespace", namespace);
// 获取配置
ConfigService configService = NacosFactory.createConfigService(properties);
String config = configService.getConfig(dataId, group, 5000);
System.out.println(config);
configService.addListener(dataId, group, new Listener() {
@Override
public Executor getExecutor() {
return null;
}
// 当配置有变化时获取通知
@Override
public void receiveConfigInfo(String s) {
System.out.println(s);
}
});
while(true) {
Thread.sleep(2000);
}
}
}
2. 执行程序
3. 查询监听
4.修改配置文件
5.查看效果