我正在进行一项执行敏感支付处理的春启动服务,并希望确保该应用程序的任何关机都不会中断这些事务。好奇如何最好地解决这个在春季启动。
我读过关于在spring中添加关闭钩子的文章,我想也许可以在类上使用一个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));
}
}我们非常感谢建设性的反馈--谢谢。
发布于 2017-10-29 10:55:54
最后,我在关闭方法上使用了@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();
}
}https://stackoverflow.com/questions/46958154
复制相似问题