Spring-IOC gracefully closes containers in non-web environments

When we design a program, we rely on the Spring container, but we don't need Spring's web environment (Spring web environment has provided graceful shutdown), that is, the program starts only by starting Spring Application Context. How can we gracefully shut down?

Designing an agent requires only Spring container management part bean s to start. The project was eventually built into an executable Jar package and started after it was built into a docker image.

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:services.xml");
        applicationContext.start();
    }
}

A bean opens a thread to perform business tasks

@Component
public class HelloLifeCycle implements Lifecycle {
    private volatile boolean running = false;
    private volatile boolean businessRunning = true;


    private ExecutorService executors = Executors.newFixedThreadPool(1);

    public HelloLifeCycle() {
        executors.execute(() -> {
            while (businessRunning) {
               //After startup,Do what business needs to do
            }
        });
    }


    public void start() {
        logger.info("lifycycle start");
        running = true;

    }

    public void stop() {
        businessRunning=false;
        logger.info("lifycycle stop ,and stop the execute");
        executors.shutdown();
        try {
            executors.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
        }
        running = false;
    }

    public boolean isRunning() {
        return running;
    }
}

The business class implements Spring's LifeCycle hook, and Spring calls back the start() and stop () methods implemented by the business class when calling its context's start() and stop () methods.

Graceful closure

If we kill the process directly, Spring will not close gracefully, and thus will not call the stop method, just like the Main startup class above.

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:services.xml");
        applicationContext.registerShutdownHook();
        applicationContext.start();
    }
}

Keywords: PHP Spring xml Docker

Added by NeilB on Thu, 10 Oct 2019 21:39:45 +0300