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.archaius</groupId>
    <artifactId>archaius-core</artifactId>
    <version>0.7.6</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</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<String> kvOpt = kvClient.getValueAsString(keyName);
        String kvStr = StringUtils.EMPTY;
        if (kvOpt.isPresent()) {
            kvStr = kvOpt.get();
        }
        Properties props = new Properties();
        props.load(new StringReader(kvStr));
        Map<String, Object> 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<String, Object> 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<String, Object> propMap = new HashMap<>();
        KeyValueClient kvClient = Consul.newClient().keyValueClient();
        Optional<String> 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值