首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring启动优雅关闭中间事务

Spring启动优雅关闭中间事务
EN

Stack Overflow用户
提问于 2017-10-26 15:23:18
回答 1查看 867关注 0票数 1

我正在进行一项执行敏感支付处理的春启动服务,并希望确保该应用程序的任何关机都不会中断这些事务。好奇如何最好地解决这个在春季启动。

我读过关于在spring中添加关闭钩子的文章,我想也许可以在类上使用一个CountDownLatch来检查线程是否已经完成了处理--如下所示:

代码语言:javascript
复制
@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));
    }
}

我们非常感谢建设性的反馈--谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-29 10:55:54

最后,我在关闭方法上使用了@PreDestroy 注解

代码语言:javascript
复制
@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();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46958154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档