对象级事务管理模式

时间:2009-01-16 12:04:48

标签: design-patterns architecture transactions

我正在尝试找出处理对象级别(而非数据库级别)事务的最佳方法。简短示例:4个对象A,B,C和D. A启动事务并调用B和C中的方法。在此事务中C也调用D.被调用的方法不应该总是参与此事务,而是也可以自己打电话。 在对象级别管理交易是否有任何模式?

我没有找到任何东西,所以我提出了这个:使用TransactionContext,其中可以注册TransactionListeners。如果使用TransactionContext启动事务,则它会将正在运行的事务注入每个已注册的侦听器,而这些侦听器将使用正在运行的事务,否则将根据需要自行启动事务。通过这种方式,我可以自由决定是否需要参与我的交易的对象。

当拥有如上所述的对象调用链时会出现问题。在启动事务时,我只知道B和C必须参与事务,因此我将它们添加到TransactionContext中。但D怎么样?我真的不想将TransactionContext传递给B和C.

我很欣赏我的方法的一些输入以及对已证实的模式的一些指示(甚至更好)。

4 个答案:

答案 0 :(得分:2)

“我真的不想将TransactionContext传递给B和C.”

为什么不呢?他们参与并委托其他对象。

无论

  • 每个人都需要注册。这意味着您必须委派注册。 A知道它移交给BC。其中每一个都可能(或可能不)有其他代表进行注册。使用“RegisterYourselfAndYourDelegatees”方法实现起来相对简单。

  • 避开Listener设计模式。创建一个事务上下文并传递它。这取代了注册和注射,设计稍微简单一些。但是,您需要有两个Context子类 - 真正的Context和不执行任何操作的存根上下文,并且在事务上下文之外使用。

    这使您的函数定义稍微复杂一些。对于Java,您可以使用重载命名来使用具有不同签名的两个方法函数。

    对于Python,这不是问题;上下文是一个可选参数。

答案 1 :(得分:1)

Spring framework(最初用于Java,但现在也有.Net版本)可以做到这一点。方法标记为:

  • 需要交易(如果没有交易,则启动一个交易);
  • 需要新的交易(始终创建新交易);

这通常使用注释完成。听起来和你所描述的完全一样。

查看Spring's transaction management

答案 2 :(得分:0)

我建议:Prevayler

Prevayler is an object persistence library for Java. It is an implementation of the
System Prevalence architectural style, in which data is kept hot in Memory with
changes journaled for system recovery.

Prevayler ' s architecture is illustrated in the diagram shown there. Prevayler [1]
serves as a transactional barrier for the business objects [2] of your application,
held in Memory. You encapsulate all modifications of your business objects into
instances of the Transaction interface [3], much like a " command " pattern
(though different from a command in some details of the pattern). Whenever 
you ask Prevayler to execute a transaction on your business objects [4], Prevayler
first writes the transaction object to a journal [5] so that data is not lost if your
system crashes. Prevayler can also write a snapshot of your entire business object
graph [6] as often as you wish. Prevayler uses the latest snapshot together with
the journals to automatically recover your business objects from disk [7] on
application startup by restoring the snapshot and then re-executing every
transaction that was originally executed after that snapshot was taken.

当然,您可以禁用持久存储并仅使用内存存储。

答案 3 :(得分:0)

强烈推荐Andrei Alexandrescu和Petru Marginean的this paper,它提出了ScopeGuard模式。这是一种优雅且非常强大的解决方案,专门用于管理特殊情况下的事务。

适用于您尝试解决的问题ScopeGuard将允许您定义事务的范围,并且轻松(意味着自动)管理您的事务是否涉及方法A,B,C,D或调用单个方法