【问题标题】:Spring boot graceful shutdown mid-transactionSpring Boot 正常关闭事务中
【发布时间】:2020-04-20 20:22:36
【问题描述】:

我正在开发一个执行敏感支付处理的 spring-boot 服务,并希望确保在不中断这些交易的情况下关闭应用程序。好奇如何在 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));
    }
}

非常感谢您提供建设性的反馈 - 谢谢。

【问题讨论】:

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


    【解决方案1】:

    我最终在关机方法上使用了@PreDestroyannotation

    @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();
        }
    }
    

    【讨论】:

    • 除了闩锁方法之外,Spring Boot 中是否有任何更新或新功能?
    猜你喜欢
    • 2021-11-14
    • 2015-04-20
    • 2019-10-05
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    相关资源
    最近更新 更多