Search in sources :

Example 1 with ConfigKVFileChangeListener

use of com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener in project polaris-java by polarismesh.

the class ConfigPropertiesFileTest method testListener.

@Test
public void testListener() throws InterruptedException {
    String content = "#some comment\nk1=10\nk2=false\nk3=5.6\nk4=1,2,3,4,5\nk5=T1\n" + "k6={\"name\":\"zhangsan\",\"age\":18,\"labels\": {\"key1\":\"value1\"}}\n" + "k7=[{\"name\":\"zhangsan\",\"age\":18,\"labels\": {\"key1\":\"value1\"}},{\"name\":\"lisi\",\"age\":20,\"labels\": {\"key1\":\"value2\"}}]";
    when(configFileRepo.getContent()).thenReturn(content);
    ConfigPropertiesFile configFile = new ConfigPropertiesFile(ConfigFileTestUtils.testNamespace, ConfigFileTestUtils.testGroup, ConfigFileTestUtils.testFileName, configFileRepo, configFileConfig);
    // modified
    AtomicBoolean k1Check = new AtomicBoolean(false);
    // delete
    AtomicBoolean k2Check = new AtomicBoolean(false);
    // not changed
    AtomicBoolean k4Check = new AtomicBoolean(false);
    // add
    AtomicBoolean k8Check = new AtomicBoolean(false);
    // modified
    AtomicBoolean k7Check = new AtomicBoolean(false);
    configFile.addChangeListener(new ConfigKVFileChangeListener() {

        @Override
        public void onChange(ConfigKVFileChangeEvent event) {
            ConfigPropertyChangeInfo k1ChangeInfo = event.getChangeInfo("k1");
            k1Check.set(k1ChangeInfo.getNewValue().equals("1") && k1ChangeInfo.getOldValue().equals("10") && k1ChangeInfo.getChangeType() == ChangeType.MODIFIED);
            ConfigPropertyChangeInfo k2ChangeInfo = event.getChangeInfo("k2");
            k2Check.set(k2ChangeInfo.getNewValue() == null && k2ChangeInfo.getOldValue().equals("false") && k2ChangeInfo.getChangeType() == ChangeType.DELETED);
            ConfigPropertyChangeInfo k4ChangeInfo = event.getChangeInfo("k4");
            k4Check.set(k4ChangeInfo == null);
            ConfigPropertyChangeInfo k8ChangeInfo = event.getChangeInfo("k8");
            k8Check.set(k8ChangeInfo.getNewValue().equals("xx") && k8ChangeInfo.getOldValue() == null && k8ChangeInfo.getChangeType() == ChangeType.ADDED);
            ConfigPropertyChangeInfo k7ChangeInfo = event.getChangeInfo("k7");
            k7Check.set(k7ChangeInfo.getChangeType() == ChangeType.MODIFIED);
        }
    });
    String newContent = "#some comment\nk1=1\nk3=5.6\nk4=1,2,3,4,5\nk5=T1\nk8=xx\n" + "k6={\"name\":\"zhangsan\",\"age\":18,\"labels\": {\"key1\":\"value1\"}}\n" + "k7=[{\"name\":\"zhangsan\",\"age\":19,\"labels\": {\"key1\":\"value1\"}},{\"name\":\"lisi\",\"age\":20,\"labels\": {\"key1\":\"value2\"}}]";
    AtomicBoolean fileCheck = new AtomicBoolean(false);
    configFile.addChangeListener(new ConfigFileChangeListener() {

        @Override
        public void onChange(ConfigFileChangeEvent event) {
            fileCheck.set(event.getNewValue().equals(newContent) && event.getOldValue().equals(content) && event.getChangeType() == ChangeType.MODIFIED);
        }
    });
    configFile.onChange(ConfigFileTestUtils.assembleDefaultConfigFileMeta(), newContent);
    TimeUnit.MILLISECONDS.sleep(500);
    Assert.assertTrue(k1Check.get());
    Assert.assertTrue(k2Check.get());
    Assert.assertTrue(k4Check.get());
    Assert.assertTrue(k8Check.get());
    Assert.assertTrue(k7Check.get());
    Assert.assertTrue(fileCheck.get());
    // 检查变更之后的值
    Assert.assertEquals(newContent, configFile.getContent());
    Assert.assertTrue(configFile.hasContent());
    Assert.assertEquals(new Integer(1), configFile.getIntProperty("k1", 8));
    Assert.assertEquals("true", configFile.getProperty("k2", "true"));
    Assert.assertTrue(configFile.getBooleanProperty("k2", true));
    Assert.assertEquals(new Float(5.6f), configFile.getFloatProperty("k3", 1.0f));
    Assert.assertEquals(new Double(5.6), configFile.getDoubleProperty("k3", 1.0));
    Assert.assertEquals("xx", configFile.getProperty("k8", ""));
    String[] arr = configFile.getArrayProperty("k4", ",", new String[] {});
    Assert.assertEquals(5, arr.length);
    for (int i = 1; i < 6; i++) {
        Assert.assertEquals(i + "", arr[i - 1]);
    }
    Assert.assertEquals(new Byte((byte) 1), configFile.getByteProperty("k1", (byte) 1));
    Assert.assertEquals(ConfigFileTestUtils.MyType.T1, configFile.getEnumProperty("k5", ConfigFileTestUtils.MyType.class, ConfigFileTestUtils.MyType.T2));
    Properties properties = configFile.asProperties();
    Assert.assertEquals(7, properties.stringPropertyNames().size());
    Assert.assertEquals("1", properties.getProperty("k1"));
    Assert.assertNull(properties.getProperty("k2"));
    Assert.assertEquals("5.6", properties.getProperty("k3"));
    Assert.assertEquals("1,2,3,4,5", properties.getProperty("k4"));
    Assert.assertEquals("T1", properties.getProperty("k5"));
    Assert.assertEquals("xx", properties.getProperty("k8"));
    ConfigFileTestUtils.User user = configFile.getJsonProperty("k6", ConfigFileTestUtils.User.class, null);
    Assert.assertNotNull(user);
    Assert.assertEquals("zhangsan", user.getName());
    Assert.assertEquals(18, user.getAge());
    Assert.assertEquals(user.getLabels().size(), 1);
    Assert.assertEquals(user.getLabels().get("key1"), "value1");
    List<ConfigFileTestUtils.User> users = configFile.getJsonProperty("k7", new TypeToken<List<ConfigFileTestUtils.User>>() {
    }.getType(), null);
    Assert.assertNotNull(users);
    Assert.assertEquals(2, users.size());
    for (ConfigFileTestUtils.User user2 : users) {
        Assert.assertNotNull(user2.getName());
        Assert.assertTrue(user2.getAge() > 0);
        Assert.assertTrue(user2.getLabels().size() > 0);
    }
}
Also used : ConfigFileChangeListener(com.tencent.polaris.configuration.api.core.ConfigFileChangeListener) Properties(java.util.Properties) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConfigPropertyChangeInfo(com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo) ConfigFileChangeEvent(com.tencent.polaris.configuration.api.core.ConfigFileChangeEvent) ConfigKVFileChangeEvent(com.tencent.polaris.configuration.api.core.ConfigKVFileChangeEvent) TypeToken(com.google.gson.reflect.TypeToken) ConfigKVFileChangeListener(com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener) ConfigPropertiesFile(com.tencent.polaris.configuration.client.internal.ConfigPropertiesFile) Test(org.junit.Test)

Example 2 with ConfigKVFileChangeListener

use of com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener in project polaris-java by polarismesh.

the class ConfigPropertiesFileExample method main.

public static void main(String[] args) throws IOException {
    String namespace = "dev";
    String fileGroup = "myGroup";
    String fileName = "application.properties";
    // 创建配置中心服务类,一般情况下只需要单例对象
    ConfigFileService configFileService = ConfigFileServiceFactory.createConfigFileService();
    // 获取 properties 格式配置文件对象
    ConfigKVFile configFile = configFileService.getConfigPropertiesFile(namespace, fileGroup, fileName);
    // 获取配置文件完整内容
    Utils.print(configFile.getContent());
    // 获取特定的 key 的值
    Utils.print(configFile.getProperty("key1", "some default value"));
    // 更多基础类型方法
    // getIntProperty、getFloatProperty ...
    // 更多高级数据结构方法
    // getEnumProperty、getArrayProperty、getJsonProperty
    // 获取 Properties
    // asProperties
    // 监听变更事件,kv类型的变更事件可以细化到 key 粒度的变更
    configFile.addChangeListener(new ConfigKVFileChangeListener() {

        @Override
        public void onChange(ConfigKVFileChangeEvent event) {
            for (String key : event.changedKeys()) {
                ConfigPropertyChangeInfo changeInfo = event.getChangeInfo(key);
                System.out.printf("\nChange info :key = %s, old value = %s, new value = %s, change type = %s\n%n", changeInfo.getPropertyName(), changeInfo.getOldValue(), changeInfo.getNewValue(), changeInfo.getChangeType());
            }
        }
    });
    System.err.println("Please input key to get the value. Input quit to exit.");
    while (true) {
        System.out.print("Input key > ");
        String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine();
        if (input == null || input.length() == 0) {
            continue;
        }
        input = input.trim();
        if ("quit".equalsIgnoreCase(input)) {
            System.exit(0);
        }
        Utils.print(configFile.getProperty(input, null));
    }
}
Also used : ConfigPropertyChangeInfo(com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo) InputStreamReader(java.io.InputStreamReader) ConfigKVFileChangeEvent(com.tencent.polaris.configuration.api.core.ConfigKVFileChangeEvent) BufferedReader(java.io.BufferedReader) ConfigKVFile(com.tencent.polaris.configuration.api.core.ConfigKVFile) ConfigKVFileChangeListener(com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener) ConfigFileService(com.tencent.polaris.configuration.api.core.ConfigFileService)

Example 3 with ConfigKVFileChangeListener

use of com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener in project polaris-java by polarismesh.

the class ConfigPropertiesFile method fireChangeEvent.

private void fireChangeEvent(ConfigKVFileChangeEvent event) {
    for (ConfigKVFileChangeListener listener : listeners) {
        notifyExecutorService.submit(() -> {
            try {
                long startTime = System.currentTimeMillis();
                listener.onChange(event);
                LOGGER.info("[Config] invoke config file change listener success. listener = {}, duration = {} ms", listener.getClass().getName(), System.currentTimeMillis() - startTime);
            } catch (Throwable t) {
                LOGGER.error("[Config] ailed to invoke config file change listener. listener = {}, event = {}", listener.getClass().getName(), event, t);
            }
        });
    }
}
Also used : ConfigKVFileChangeListener(com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener)

Example 4 with ConfigKVFileChangeListener

use of com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener in project polaris-java by polarismesh.

the class ConfigYamlFileExample method main.

public static void main(String[] args) throws IOException {
    String namespace = "dev";
    String fileGroup = "myGroup";
    // 文件名通过 / 分割在管控端按目录格式展示
    String fileName = "root/bootstrap.yaml";
    // 创建配置中心服务类,一般情况下只需要单例对象
    ConfigFileService configFileService = ConfigFileServiceFactory.createConfigFileService();
    // 获取 yaml 格式配置文件对象,这里是唯一跟 properties 格式区别的地方
    ConfigKVFile configFile = configFileService.getConfigYamlFile(namespace, fileGroup, fileName);
    // 获取配置文件完整内容
    Utils.print(configFile.getContent());
    // 获取特定的 key 的值
    Utils.print(configFile.getProperty("key1", "some default value"));
    // 更多基础类型方法
    // configFile.getIntProperty()、configFile.getFloatProperty() ...
    // 更多高级数据结构方法
    // configFile.getEnumProperty()、configFile.getArrayProperty()、configFile.getJsonProperty()
    // 获取 Properties
    // configFile.asProperties()
    // 监听变更事件,kv类型的变更事件可以细化到 key 粒度的变更
    configFile.addChangeListener(new ConfigKVFileChangeListener() {

        @Override
        public void onChange(ConfigKVFileChangeEvent event) {
            for (String key : event.changedKeys()) {
                ConfigPropertyChangeInfo changeInfo = event.getChangeInfo(key);
                System.out.printf("\nChange info :key = %s, old value = %s, new value = %s, change type = %s\n%n", changeInfo.getPropertyName(), changeInfo.getOldValue(), changeInfo.getNewValue(), changeInfo.getChangeType());
            }
        }
    });
    System.err.println("Please input key to get the value. Input quit to exit.");
    while (true) {
        System.out.print("Input key > ");
        String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine();
        if (input == null || input.length() == 0) {
            continue;
        }
        input = input.trim();
        if ("quit".equalsIgnoreCase(input)) {
            System.exit(0);
        }
        Utils.print(configFile.getProperty(input, null));
    }
}
Also used : ConfigPropertyChangeInfo(com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo) InputStreamReader(java.io.InputStreamReader) ConfigKVFileChangeEvent(com.tencent.polaris.configuration.api.core.ConfigKVFileChangeEvent) BufferedReader(java.io.BufferedReader) ConfigKVFile(com.tencent.polaris.configuration.api.core.ConfigKVFile) ConfigKVFileChangeListener(com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener) ConfigFileService(com.tencent.polaris.configuration.api.core.ConfigFileService)

Aggregations

ConfigKVFileChangeListener (com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener)4 ConfigKVFileChangeEvent (com.tencent.polaris.configuration.api.core.ConfigKVFileChangeEvent)3 ConfigPropertyChangeInfo (com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo)3 ConfigFileService (com.tencent.polaris.configuration.api.core.ConfigFileService)2 ConfigKVFile (com.tencent.polaris.configuration.api.core.ConfigKVFile)2 BufferedReader (java.io.BufferedReader)2 InputStreamReader (java.io.InputStreamReader)2 TypeToken (com.google.gson.reflect.TypeToken)1 ConfigFileChangeEvent (com.tencent.polaris.configuration.api.core.ConfigFileChangeEvent)1 ConfigFileChangeListener (com.tencent.polaris.configuration.api.core.ConfigFileChangeListener)1 ConfigPropertiesFile (com.tencent.polaris.configuration.client.internal.ConfigPropertiesFile)1 Properties (java.util.Properties)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 Test (org.junit.Test)1