1

How can I control programmatically start up of app depending of config server? I have sh script for controlling on docker-compose up, but I’m wondering can I control it programly in the spring app.

Regards

sherybedrock
  • 63
  • 10

1 Answers1

0

If you are on Ubuntu then the following solution will work flawless. If you are on a different distro and if ps -A doesn't work, then kindly find the equivalent one. Now, talking about the strategy how it is done below. I wanted my application to be started by a script as it contains some JVM arguments. So when my application will be running, the script will also be in the active process list. After the startup is completed, the application finds whether my script file is present in the active process list or not. If it's not there then it shuts down the application. The following example will probably give you an idea on how to implement the same with the config server.

@Autowired
private ApplicationContext context;

@EventListener(ApplicationReadyEvent.class) // use in production
public void initiateStartup() {

    try {
        String shProcessName = "root-IDEA.sh";
        String line;
        boolean undesiredStart = true;

        Process p = Runtime.getRuntime().exec("ps -A");
        InputStream inputStream = p.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        while ((line = bufferedReader.readLine()) != null) {

            if (line.contains(shProcessName)) {
                undesiredStart = false;
                break;
            }
        }

        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();

        if (undesiredStart) {
            System.out.println("--------------------------------------------------------------------");
            System.out.println("APPLICATION STARTED USING A DIFFERENT CONFIG. PLEASE START USING THE '.sh' FILE.");
            System.out.println("CLOSING APPLICATION");
            System.out.println("--------------------------------------------------------------------");

            // close the application
            int exitCode = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);
            System.exit(exitCode);
        }

        System.out.println("APPLICATION STARTED CORRECTLY");

    } catch (IOException e) {
        e.printStackTrace();
    }
}
sam
  • 1,800
  • 1
  • 25
  • 47