SpringBoot + Docker realizes dynamic configuration of attributes

The author was too young back then, as the posture grew, there was a better way. It was 9102. Update it again,
as follows, in the yml file of spring boot

spring:
    redis:
        database: ${REDIS_DATABASE:1}

Pay attention to $ {REDIS_DATABASE: 1}, what does this mean, if you have the variable REDIS_DATABASE in your environment variable, the value in your environment variable is the main one, if there is no default,
it is 1, so
if it is docker, you can Follow docker run with -e = "REDIS_DATABASE = 1",
if the jar is started, you can java -jar xx.jar --REDIS_DATABASE = 1,
so as to dynamically specify the parameters you need to change ~


Sometimes, we will package the project into a docker image,
but because of the different fixed configuration properties in the project,
the things that docker will do after running are also different.
If you can not dynamically configure the properties,
this is a very bad thing. Because there may be more than a dozen different attributes, the
stupid way is to change the attributes one by one, pack them one by one, and pack them into a dozen mirrors. If you do n’t pay attention to the mistakes, you will have to repackage them, which is really hurt.

So I thought of an implementation of dynamic configuration below, the
idea is -e "attribute name = attribute value" when docker run,
when the Boot project starts, through System.getenv ("attribute name"),
after getting the attribute value, add Go to the configuration of the boot, and
then handle it according to the business
. Write the blog for the first time. Please bear with me for the mistakes. If there is a better method or idea, please enlighten me. The following is the code.

public static void main(String[] args) {

        SpringApplication springApplication = new SpringApplication(YourApplication.class);

        Map<String,Object> map = new HashMap<>();
        String yourPropties = System.getenv("yourPropties");
        if(yourPropties == null || "".equals(yourPropties.trim())){
            throw new NullPointerException("系统没有获取到yourPropties环境变量参数!");
        }else if(SystemParams.yourPropties.get(yourPropties) == null){
            throw new NullPointerException("yourPropties环境变量参数在程序中不存在!");
        }
        logger.info("=================="+yourPropties+"==================");
        map.put("env.yourPropties",yourPropties);
        springApplication.setDefaultProperties(map);
        springApplication.run(args);
    }

Published 38 original articles · praised 17 · views 9026

Guess you like

Origin blog.csdn.net/cainiao1412/article/details/73945144