簡體   English   中英

Spring boot 在事務中正常關機

[英]Spring boot graceful shutdown mid-transaction

我正在開發一個執行敏感支付處理的 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));
    }
}

非常感謝建設性的反饋 - 謝謝。

我最終在關閉方法上使用了@PreDestroy 注釋

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM