dimanche 13 février 2022

Loading and sharing configuration data in an Akka project

/Users/aronayne/projects/code-scraps/src/main/java/q2

Title

Pattern for reading Akka configuration into an application.

Body

I’ve defined two applicaiton.conf files, one for each environment dev and prod :

application-dev.conf application-prod.conf

To read the configuration values I use a config object builder (using lombok) named ConfigurationObject to set the values read from the application configuration files. The configuration object just stores two properties ‘kafkaBrokers’ and ‘someOtherConfig’ :

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigLoader {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigLoader.class);

    public static void main(String[] args) {

        String env = "dev";
        final Config configDev = ConfigFactory.load("application-"+env+".conf");
        final ConfigurationObject configurationObjectDev = ConfigurationObject.builder()
                .kafkaBrokers(configDev.getString("kafka-config.brokers"))
                .someOtherConfig(configDev.getString("kafka-config.brokers"))
                .build();

        env = "prod";
        final Config configProd = ConfigFactory.load("application-"+env+".conf");
        final ConfigurationObject configurationObjectProd = ConfigurationObject.builder()
                .kafkaBrokers(configProd.getString("kafka-config.brokers"))
                .someOtherConfig(configProd.getString("kafka-config.brokers"))
                .build();

        LOGGER.info(configurationObjectDev.toString());
        LOGGER.info(configurationObjectProd.toString());

    }
}

Here I’ve defined the configuration object to store the values read from application.conf :

import lombok.Builder;
import lombok.ToString;

@Builder
@ToString
public class ConfigurationObject {
    final String kafkaBrokers;
    final String someOtherConfig;
}

Should I just use ConfigFactory.load directly instead of wrapping each property from a given environment application.conf to a configuration object, in this case ConfigLoader. Is there a pattern I should use for this ?

Application conf files :

application-dev.conf :

kafka-config {
    brokers="broker1,broker4"
    brokers = ${?MY_KEY_ENV}
}

some-other-config {
    brokers="broker-prod1,broker-prod4"
    brokers = ${?MY_KEY_ENV}
}

application-prod.conf :

kafka-config {
    brokers="broker-prod1,broker-prod4"
}
some-other-config {
    brokers="broker-prod1,broker-prod4"
   brokers = ${?MY_KEY_ENV}
}

Aucun commentaire:

Enregistrer un commentaire