延迟发送邮件直到事务提交
有人对如何实现自己的 XAResource 有好的教程或建议吗?我需要 Spring 的 MailSender 是事务性的,以便只有在事务提交后才会发送邮件,并且似乎没有任何现有的事务性包装器。
Does anyone have a good tutorial or some advice on how to implement one's own XAResource? I need Spring's MailSender to be transactional, so that the mail will only be sent once the transaction commits, and it seems there isn't any existing transactional wrapper.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您只需要等待提交,正如您在评论中所说,您可以使用
TransactionSynchronizationManager.registerSynchronization()
触发提交时发送电子邮件。If you just need to wait for the commit, as you say in a comment, you can investigate using
TransactionSynchronizationManager.registerSynchronization()
to trigger email sending on commit.您可以将
TransactionSynchronizationManager.registerSynchronization
(如提到的 gpeche)与TransactionSynchronizationAdapter
一起使用,它具有在事务的各个阶段调用的各种方法。当前交易。我认为最适合这个问题的方法是 afterCommit。You can use a
TransactionSynchronizationManager.registerSynchronization
(like gpeche mentioned) with aTransactionSynchronizationAdapter
which has a variety of methods that are called at various stages of the current transaction. I think the most suitable method for the question is the afterCommit.我怀疑是否有可能为 SMTP 实现真正的 XAResource。资源管理器(在本例中为 SMTP 服务器)上应该有事务支持,但我不相信有任何事务支持。我想说你最好的选择是“最后一个资源提交”模式 - 它允许一个非 XA 资源参与 XA 事务。谷歌搜索一下,有很多信息。大多数 Java EE 服务器都支持这一点。
I doubt that it's possible to implement true XAResource for SMTP. There should be transaction support on the resource manager (SMTP server in this case) and I don't believe there are any. I would say your best bet is 'Last resource commit' pattern - which allows one non XA resource participate in XA transaction. Search Google, there are plenty of info. Most Java EE servers supports this.
除了 gpeche 提到的选项之外,另一种选项是从事务内发送事务性 JMS 消息。然后让消息侦听器(例如MDB bean)发送电子邮件。
EJB 中的另一个技巧是在事务内调度计时器。计时器也是事务性的,并且仅在事务提交时才会启动。只需使用一个超时 = 0 的计时器,这样它将在事务提交后立即启动。
One other option next to the one mentioned by gpeche, is sending a transactional JMS message from within the transaction. Then let the message listener (like e.g. a MDB bean) send the email.
Another trick in EJB is scheduling a timer from within a transaction. The timer is also transactional and will only be started when the transaction commits. Simply use a timer with timeout = 0, so it will start immediately after the transaction commits.