Spring启动正常关闭中间事务

时间:2017-10-26 15:23:18

标签: spring-boot transactional thread-synchronization shutdown-hook

我正在开发执行敏感付款处理的spring-boot服务,并且希望确保在不中断这些交易的情况下完成对应用的任何关闭。好奇如何在春季开机时最好地接近这个。

我读到了关于向spring-boot添加关闭钩子的问题,我想也许可以在类上使用CountDownLatch来检查线程是否已完成处理 - 如下所示:

@Service
public class PaymentService {

    private CountDownLatch countDownLatch;

    private void resetLatch() {
        this.countDownLatch = new CountDownLatch(1);
    }

    public void processPayment() {
        this.resetLatch();

        // do multi-step processing

        this.CountDownLatch.countDown();
    }

    public void shutdown() {
        // blocks until latch is available 
        this.countDownLatch.await();
    }
}

// ---

@SpringBootApplication
public class Application {
    public static void main(String[] args) {

        // init app and get context
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

        // retrieve bean needing special shutdown care
        PaymentService paymentService = context.getBean(PaymentService.class);

        Runtime.getRuntime().addShutdownHook(new Thread(paymentService::shutdown));
    }
}

非常感谢建设性反馈 - 谢谢。

1 个答案:

答案 0 :(得分:1)

我最终在关机方法上使用@PreDestroy annotation

@Service
public class PaymentService {

    private CountDownLatch countDownLatch;

    private synchronized void beginTransaction() {
        this.countDownLatch = new CountDownLatch(1);
    }

    private synchronized void endTransaction() {
        this.countDownLatch.countDown();
    }

    public void processPayment() {
        try {
            this.beginTransaction();

            // - - - - 
            // do multi-step processing
            // - - - -

        } finally {
            this.endTransaction();
        }
    }

    @PreDestroy
    public void shutdown() {
        // blocks until latch is available 
        this.countDownLatch.await();
    }
}