提交交易然后发送电子邮件
在 Java 中,假设我有一个事务,一旦提交,我想要执行另一个操作,在本例中是发送电子邮件。
因此,
try {
transaction.begin()
...
transaction.commit()
// point 1
Utility.sendEmail(...)
} catch (Exception e) {
transaction.rollback();
}
线程是否有可能在第 1 点死亡/被杀死并且不发送电子邮件? 有什么办法可以尽量减少这种情况吗?也许是 JTA + JMS,发送消息的操作是事务的一部分? 我正在调查一个问题并探索这是否可能。 JVM 仍然存在(没有 OOM)。我不知道应用程序服务器的内部工作原理,所以不确定这是否可能。
In Java, let's say I have a transaction that once it is committed, I want to do another action, in this case, send an email.
Therefore,
try {
transaction.begin()
...
transaction.commit()
// point 1
Utility.sendEmail(...)
} catch (Exception e) {
transaction.rollback();
}
Is it possible for the thread to die/get killed at point 1 and not send an email ?
Any way to minimize this ? JTA + JMS perhaps, where the action of sending a message is part of a transaction ?
I'm investigating an issue and exploring whether this is possible. JVM is still alive (no OOM). I do not know the inner working of the app server so not sure if this is possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果 commit() 正常并且 sendEmail() 抛出异常,我不能确定 catch 子句中的 rollback() 是否有任何效果。测试这一点的最快方法是从 sendEmail() 方法引发异常并查看事务是否实际提交。
我的说法是,将 sendEmail() 调用移出 try 块:
这样您就可以控制回滚时会发生什么。
另外,我认为在大多数情况下将电子邮件发送到 JMS 队列是一个好主意。这样做将授予您的数据库代码继续的权限,并据称向您的用户提供反馈,表明一切顺利,并且只要符合电子邮件控制器的时间表,就会发送电子邮件。例如,您的电子邮件服务器可能存在连接问题,并且电子邮件发送会在抛出异常之前挂起 30 秒,您的用户会将此视为一次很长时间的按钮单击。
I can't say for sure if the rollback() in the catch clause has any effect if the commit() was OK and sendEmail() threw an exception. The quickest way to test this is to throw an exception from the sendEmail() method and see if the transaction was actually committed.
The way I would put it though, is to move the sendEmail() call away from your try block:
This way you can control what will happen if a rollback was made.
Also, I think that sending the email to a JMS queue is in most cases a good idea. Doing it like that will give your DB code permission to continue and supposedly give feedback to your user that everything went OK and the email will be sent whenever it fits the email controller's schedule. For example, there might be a connection issue with your email server and the email sending would hang for say 30 seconds before throwing an exception and your user would see this as a very long button click.