1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| /** * 获取nacos配置 */ @Test public void test01() throws NacosException { Properties properties = new Properties(); /* 设置地址 */ properties.put(PropertyKeyConst.SERVER_ADDR,"127.0.0.1:8848"); /* 设置名称空间 命名空间的值是命名空间ID,不能是命名空间的名字 如果不设置命名空间,那么默认读取自带的public空间 */ properties.put(PropertyKeyConst.NAMESPACE,"26df001f-7eaa-49eb-95fe-8a28f6acdb7e"); /* 获取配置服务实例 */ ConfigService configService = NacosFactory.createConfigService(properties); /* 获取配置实例 第一个参数(dataId): 命名空间下的自定义的 dataId 值 第二个参数(group): 命名空间下的自定义的 group 值 第三个参数(timeoutMs): 读取数据的超时时间 */ String config = configService.getConfig("tmall", "DEFAULT_GROUP", 3000); System.out.println(config); }
/* * 监听数据变化 */ @Test public void test02() throws NacosException { Properties properties = new Properties(); /* 设置地址 */ properties.put(PropertyKeyConst.SERVER_ADDR,"127.0.0.1:8849"); /* 设置名称空间 命名空间的值是命名空间ID,不能是命名空间的名字 如果不设置命名空间,那么默认读取自带的public空间 */ properties.put(PropertyKeyConst.NAMESPACE,"26df001f-7eaa-49eb-95fe-8a28f6acdb7e"); /* 获取配置服务实例 */ ConfigService configService = NacosFactory.createConfigService(properties); /* 获取配置实例 第一个参数(dataId): 命名空间下的自定义的 dataId 值 第二个参数(group): 命名空间下的自定义的 group 值 第三个参数(timeoutMs): 读取数据的超时时间 */ String config = configService.getConfig("tmall", "DEFAULT_GROUP", 3000); System.out.println(config); //给当前配置(configService)添加监听器 configService.addListener("tmall", "DEFAULT_GROUP", new Listener() { public void receiveConfigInfo(String configInfo) { System.out.println("我是监听器我被触发了...配置信息为:"+configInfo); } public Executor getExecutor() { return null; } }); /* * 防止程序执行完退出,保持进程不退出. * 在正式项目中项目进程不需要这段代码守护,可以删除 */ while (true) { try { Thread.sleep(1000); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); System.out.println("监听中...当前时间: "+sdf.format(new Date(System.currentTimeMillis()))); } catch (InterruptedException e) { e.printStackTrace(); } } }
请多案例请去官网查看: https://nacos.io/zh-cn/docs/sdk.html
|