gpt4 book ai didi

java - 基于另一个线程结果的数据库回滚

转载 作者:行者123 更新时间:2023-12-02 10:58:00 25 4
gpt4 key购买 nike

我对业务逻辑进行了顺序处理,其中包括:

  1. 将消息发送到远程服务器
  2. 将该消息保存到数据库

顺序.java

try {
sender.send(message); // throws SendingException
} catch (SendingException e) {throw SomeException("Couldn't send.", e);}

dbService.save(message); // save only if successfully sent

我意识到,如果并行执行这两项任务,就可以提高性能。一个线程发送消息,另一个线程将消息保存到数据库。

并行.java

// send: 1st thread
executor.execute(() -> {
try {
sender.send(message);
} catch(SendingException e) {throw SomeException("Couldn't send.", e);}

});

// save: 2nd thread
executor.execute(() -> dbService.save(message));

并行方法的问题在于,即使发生异常,消息也会保存到数据库中。如果发生异常,有什么方法可以防止保存,但仍然并行运行这两个任务?

也许是某种基于触发器的回滚。

最佳答案

保存并提交数据后,您将无法回滚事务。现在,您从不同的线程发送消息,而不是从您将消息保存消息到数据库的线程。因此,您的消息有可能在发送消息之前保存到数据库,在这种情况下,如果发送消息期间出现任何异常,则无法回滚。我建议使用 CompletableFuture 如下所示:

CompletableFuture.supplyAsync(() -> {
// send message from here
System.out.println("Msg send");
return msg;
}).exceptionally(ex -> {
// handle the exception
System.out.println("Exception occour");
return "";
}).thenAccept((msgTosave) -> {
if (!msgTosave.isEmpty()) {
// save your msg to db here
System.out.println("Msg To save : " + msgTosave);
}
});

关于java - 基于另一个线程结果的数据库回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51570569/

25 4 0