spring-boot integrate with archaius

Prerequistion

I will use Consul-KV as the property source, you can refer to below article to setup the consul environment
https://blog.csdn.net/yaominhua/article/details/82316287
Also you need integrate with consul client first, please refer to below article
https://blog.csdn.net/yaominhua/article/details/82317368

Objective

To retrieve the configuration dynamically

Steps

Add below dependency to pom.xml

<dependency>
    <groupId>com.netflix.archaiusgroupId>
    <artifactId>archaius-coreartifactId>
    <version>0.7.6version>
dependency>
<dependency>
    <groupId>org.apache.commonsgroupId>
    <artifactId>commons-configuration2artifactId>
    <version>2.3version>
dependency>
<dependency>
    <groupId>org.apache.commonsgroupId>
    <artifactId>commons-lang3artifactId>
dependency>

Implements the interface PolledConfigurationSource

public class ConsulConfigurationSource implements PolledConfigurationSource {

    private String keyName;

    public ConsulConfigurationSource(String keyName) {
        this.keyName = keyName;
    }

    @Override
    public PollResult poll(boolean initial, Object checkPoint) throws Exception {
        KeyValueClient kvClient = Consul.newClient().keyValueClient();
        Optional kvOpt = kvClient.getValueAsString(keyName);
        String kvStr = StringUtils.EMPTY;
        if (kvOpt.isPresent()) {
            kvStr = kvOpt.get();
        }
        Properties props = new Properties();
        props.load(new StringReader(kvStr));
        Map propMap = new HashMap<>();
        props.keySet().forEach(x -> {
            propMap.put((String)x, props.get(x));
        });
        return PollResult.createFull(propMap);
    }

}

Create custom spring application initializer

public class ConsulPropertySourceInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    // default value is 60000 (60s)
    private static final String ARCHAIUS_DELAY_KEY_MILLS = "archaius.fixedDelayPollingScheduler.delayMills";

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.setProperty(ARCHAIUS_DELAY_KEY_MILLS, "10000");
        // This key/value has been added from Consul-UI
        String keyName = "service/config/dev";
        PolledConfigurationSource configSource = new ConsulConfigurationSource(keyName);
        AbstractPollingScheduler scheduler = new FixedDelayPollingScheduler();
        DynamicConfiguration configuration = new DynamicConfiguration(configSource, scheduler);
        ConfigurationManager.install(configuration);
    }

}

Add this initializer into spring application before run

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication sa = new SpringApplication(Application.class);
        // add custom initializer
        sa.addInitializers(new ConsulPropertySourceInitializer());
        sa.run(args);
    }

}

Write the test controller to retrieve the data

@RestController
@RequestMapping("helloWorld")
public class HelloWorldController {
    @RequestMapping(value="property/{propName}")
    public String getPropertyValue(@PathVariable("propName") String propName) {
        DynamicStringProperty dsp = DynamicPropertyFactory.getInstance().getStringProperty(propName, "");
        return dsp.get();
    }
}

We can use below URL to have a test:
http://localhost:8080/helloWorld/property/person.first.name

Put the data into spring application property source

Create custom property source

public class ConsulPropertySource extends MapPropertySource {
    public ConsulPropertySource(String name, Map source) {
        super(name, source);
    }
}

Create custom environment post processor

public class LoadConsulEnv implements EnvironmentPostProcessor, Ordered {

    @Override
    public int getOrder() {
        return ConfigFileApplicationListener.DEFAULT_ORDER + 1;
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map propMap = new HashMap<>();
        KeyValueClient kvClient = Consul.newClient().keyValueClient();
        Optional kvOpt = kvClient.getValueAsString("service/config/dev");
        String kvStr = StringUtils.EMPTY;
        if (kvOpt.isPresent()) {
            kvStr = kvOpt.get();
        }
        Properties props = new Properties();
        try {
            props.load(new StringReader(kvStr));
        } catch (IOException e) {
            e.printStackTrace();
        }
        props.keySet().forEach(x -> {
            propMap.put((String)x, props.get(x));
        });
        ConsulPropertySource propertySource = new ConsulPropertySource("thirdEnv", propMap);
        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.addLast(propertySource);
    }
}

Register the processor to spring.factories

  • Create folder “META-INF” under src/main/resources
  • Create file “spring.factories” under folder “META-INF”
  • Copy below content to the file
org.springframework.boot.env.EnvironmentPostProcessor=\
 com.xuya.app.demo.config.archaius.LoadConsulEnv
  • LoadConsulEnv will be loaded when application run

Create a test controller to have a test

@RestController
@RequestMapping("helloWorld")
public class HelloWorldController {
    @Autowired
    private Environment env;
    @RequestMapping(value="envprop/{propName}")
    public String getEnvPropertyValue(@PathVariable("propName") String propName) {
        return env.getProperty(propName);
    }
}

We can use below URL to have a test:
http://localhost:8080/helloWorld/envprop/person.first.name

你可能感兴趣的:(spring-boot,微服务,archaius)