Как прочитать значение ключа XML-файла, используя Netflix Archaius API?

Я новичок в Netflix Archaius. Кто-нибудь может предоставить пример кода для чтения значения ключа из XML-файла? Также хотелось бы, чтобы значения обновлялись автоматически при изменении любого ключа в файле XML...

С уважением, Ашиш

1 ответ

Пример JUnit о том, как использовать xml для пар ключ / значение и использовать Archaius для автоматической загрузки изменений:

Важное примечание к примеру кода: программа завершается после первого обратного вызова. Если вы хотите проверить больше обратных вызовов, увеличьте счетчик в переменной класса 'latch'

package com.apple.paymentgateway.config;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.configuration.XMLPropertiesConfiguration;
import org.junit.Test;

import com.netflix.config.AbstractPollingScheduler;
import com.netflix.config.ConcurrentMapConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicConfiguration;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.config.FixedDelayPollingScheduler;
import com.netflix.config.PollResult;
import com.netflix.config.PolledConfigurationSource;

public class TestArchaius {
    CountDownLatch latch = new CountDownLatch(1);

    @Test
    public void tes() throws Exception {
        AbstractPollingScheduler scheduler = new FixedDelayPollingScheduler(0, 1000, false);
        DynamicConfiguration dynamicConfiguration = new DynamicConfiguration(new MyPolledConfigurationSource(), scheduler);

        ConfigurationManager.install(dynamicConfiguration);

        DynamicStringProperty fieldsProperty = DynamicPropertyFactory.getInstance().getStringProperty("key1", "");
        fieldsProperty.addCallback(() -> {
            System.out.println(fieldsProperty.get());
            latch.countDown();
        });

        latch.await();
    }

    class MyPolledConfigurationSource implements PolledConfigurationSource {

        @Override
        public PollResult poll(boolean initial, Object checkPoint) throws Exception {
            ConcurrentMapConfiguration configFromPropertiesFile = new ConcurrentMapConfiguration(
                    new XMLPropertiesConfiguration("test.xml"));
            Map<String, Object> fullProperties = new HashMap<String, Object>();
            configFromPropertiesFile.getProperties().forEach((k, v) -> fullProperties.put((String) k, v));
            return PollResult.createFull(fullProperties);
        }

    }
}

test.xml:

     <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
     <properties>
       <comment>Description of the property list</comment>
       <entry key="key1">value1</entry>
       <entry key="key2">value2</entry>
       <entry key="key3">value3</entry>
     </properties>
    

Другие вопросы по тегам