英文:
Separate transaction on Java spring
问题
我对如何完成这个任务不太确定。但我正在寻找一种将函数的交易分开的方法。
我有一个处理每条消息结果的监听器(messageListener
)。在将其发送到下一步(sendToNextProcess
)之前,我想确保第一个交易(updateMessagesResults
)成功。(也许要创建一个单独的交易?)
在Java Spring中,我该如何做?谢谢
public void messageListener(List<Message> messages) {
resultUpdater.updateMessagesResults(messages);
sendToNextProcess(messages);
}
注意:监听器和resultUpdater都有@Transactional
注释。
谢谢!
英文:
I'm not quite sure on how to do this. But I'm finding a way to separate the transactions of the functions.
I have a listener that processes the results of each messages (messageListener
). And before sending it to the next step (sendToNextProcess
), I'd like to make sure that the first transaction(updateMessagesResults
) was successful. (Create a separate transaction perhaps?)
How do I do this on Java Spring? Thank you
public void messageListener(List<Message> messages) {
resultUpdater.updateMessagesResults(messages);
sendToNextProcess(messages);
}
Note: Both the listener and the resultUpdater have the @Transactional
annotations.
Thank you!
答案1
得分: 2
在sendToNextProcess
和updateMessagesResults
上都添加REQUIRES_NEW
,
并且不要直接调用sendToNextProcess
,因为这样不会起作用,你应该注入当前的服务,然后像这样调用它:
@Service
public class CurrentService {
@Autowired
private CurrentService currentService;
@Transactional
public void messageListener(List<Message> messages) {
resultUpdater.updateMessagesResults(messages);
currentService.sendToNextProcess(messages);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void sendToNextProcess(List<Message> messages) {
}
}
为什么要从注入的服务中调用它?因为@Transactional
会尝试从类的范围外部进行包装,然后尝试使用this
调用它,但实际效果不如预期。
英文:
Add REQUIRES_NEW
on both sendToNextProcess
and updateMessagesResults
and don't call sendToNextProcess
directly because it will not work you should inject the current service and call it from like this
@Service
public CurrentService {
@Autowire
CurrentService CurrentService;
@Transactional
public void messageListener(List<Message> messages) {
resultUpdater.updateMessagesResults(messages);
currentService.sendToNextProcess(messages);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void sendToNextProcess(List<Message> messages) {
}
}
why you should call it from injected service because the @transactional
tries to wrap it from outside the class scope and then it tries to call it with this
and it will not work as you expect
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论