.NET可逆框架设计

开发 架构 后端
前段时间一直在学习和研究.NET事务处理,慢慢的我发现可以使用事务处理来实现一种可逆的系统框架。这种框架在一些IT社区似乎还没有见过,但是在我们日常开发中确实有这个需求。所以我花了点时间深入的研究了一下事务的原理和使用,实现了以事务为纽带,以资源为操作对象的可逆框架。

前段时间一直在学习和研究.NET事务处理,慢慢的我发现可以使用事务处理来实现一种可逆的系统框架。这种框架在一些IT社区似乎还没有见过,但是在我们日常开发中确实有这个需求。所以我花了点时间深入的研究了一下事务的原理和使用,实现了以事务为纽带,以资源为操作对象的可逆框架。

这里我假设您对事务有了整体的认识,也对自定义事务管理器有过了解。[王清培版权所有,转载请给出署名]

(可以参考本人的:.NET简谈事务本质论.NET简谈自定义事务资源管理器)

1.    什么是可逆的程序框架

什么叫可逆的?程序的执行是可以被无限制回滚的。

什么叫可逆的框架?实现了对可逆功能的封装,并能通过简单的接口调用进行使用。框架可能有大有小,我想这么称呼它是为了表达它的整体性和重要性。

那么到底可逆的需求在哪里?其实在我们开发程序的时候经常会使用事务来进行业务的控制。比如删除订单,然后删除订单明细等等,对于这样的要求很多,我们只能将逻辑控制在一个事务范围内,不能在没有事务性的逻辑代码中编写这种要求的业务功能。等出现未知错误的时候在进行事务的回滚。

你也许会问,使用原来的事务处理不是也能进行回滚吗?当然不是这么简单的,我们使用事务回滚时只能将资源回滚到最初未进行事务处理前的状态。(这里不仅仅指的是数据库事务,而是全局的事务处理) 我们用图做个比较。[王清培版权所有,转载请给出署名]

传统的事务处理图:

可逆的事务处理图:

从这两幅图中我们可以很明显的看出,传统的事务处理在事务处理的过程当中无法控制中间数据,也就是说无法对事务处理进行分段,然后在进行统一的提交或回滚。

在可逆框架的事务处理里我们就可以控制事务的执行阶段,在必要的时候我们只需提交或者回滚某一阶段的数据。

1.1环境事务

在可逆框架的事务处理图中,我们看到事务的开始,然后就进行下一步、下一步这样的操作。在每进行一个下一步操作的时候,就是进入到了一个子事务里处理,在.NET中是可以进行事务的嵌套,其实也就是依赖事务Dependent Transaction实现。通过使用环境事务可以让事务性感知代码能自动的识别出您将要使用事务进行操作。所以在每进行下一步操作的时候,只有将当前环境事务切换为您将依赖的子事务才行。如果只是单纯的使用依赖事务对象实例在使用,那么将无法进行诸多其他的事务处理。

2可逆框架的实现原理

由于我们只能控制自定义事务资源管理器的内部实现,所以我们在构建自己的数据处理时问题变的简单多了。

实现可逆框架的核心技术就是使用依赖事务进行事务的克隆操作。将一个大的事务处理逻辑上切割成多了小的事务操作,然后在进行统一的提交或回滚。

在实现上其实就是将Committable Transaction对象进行包装,实现简单的调用接口。这里参照了环境代码的概念,将对象的生命周期控制在代码片段中。

2.1自定义资源管理器的实现

我们需要扩展IEnlistmentNotification接口的实现,加入对“上一步”、“下一步”的数据操作。

请看代码:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.  using System.Transactions;  
  10.    
  11.  namespace ReversibleLib  
  12.  {  
  13.      /// <summary>  
  14.      /// 可逆范围内的资源管理器。  
  15.      /// 可以使用该类对易失性资源进行事务范围内的管理。在事务操作范围内进行可逆操作。  
  16.      /// </summary>  
  17.      /// <typeparam name="T">需要管理的资源类型</typeparam>  
  18.      /// <typeparam name="Xcopy">资源在使用、恢复过程中的数据复制对象。</typeparam>  
  19.      public class ReResourceManager<T, Xcopy> : IEnlistmentNotification, IReversibleGetResourceData<T>  
  20.          where T : classnew()  
  21.          where Xcopy : class 
  22.      {  
  23.          /// <summary>  
  24.          /// 私有字段。资源的持久引用。  
  25.          /// </summary>  
  26.          T _commitfrontvalue;  
  27.          /// <summary>  
  28.          /// 私有字段。事务性操作数据对象。  
  29.          /// </summary>  
  30.          T _rollbackfrontvalue = new T();  
  31.          /// <summary>  
  32.          /// 保存数据复制对象。  
  33.          /// </summary>  
  34.          Xcopy _copy;  
  35.          /// <summary>  
  36.          /// 泛型约束需要,内部使用。  
  37.          /// </summary>  
  38.          public ReResourceManager() { }  
  39.          /// <summary>  
  40.          /// 资源管理器内部名称。便于追踪  
  41.          /// </summary>  
  42.          public string Name { getset; }  
  43.          /// <summary>  
  44.          /// 重载默认构造函数,使用资源类型和数据复制对象初始化资源管理器。  
  45.          /// </summary>  
  46.          public ReResourceManager(T t, Xcopy icopy)  
  47.          {  
  48.              (icopy as IResourceCopy<T>).Copy(_rollbackfrontvalue, t);  
  49.              _commitfrontvalue = t;  
  50.              _copy = icopy;  
  51.          }  
  52.    
  53.          #region IEnlistmentNotification 成员  
  54.          public void Prepare(PreparingEnlistment preparingEnlistment)  
  55.          {  
  56.              preparingEnlistment.Prepared();  
  57.          }  
  58.          public void Commit(Enlistment enlistment)  
  59.          {  
  60.              enlistment.Done();  
  61.          }  
  62.          public void InDoubt(Enlistment enlistment)  
  63.          {  
  64.              enlistment.Done();  
  65.          }  
  66.          public void Rollback(Enlistment enlistment)  
  67.          {  
  68.              (_copy as IResourceCopy<T>).Copy(_commitfrontvalue, _rollbackfrontvalue);//回滚事务  
  69.              enlistment.Done();  
  70.          }  
  71.          #endregion  
  72.    
  73.          #region IReversibleGetResourceData<T> 成员  
  74.          T IReversibleGetResourceData<T>.GetPreviousData()  
  75.          {  
  76.              T result = new T();  
  77.              (_copy as IResourceCopy<T>).Copy(result, _rollbackfrontvalue);  
  78.              return result;  
  79.          }  
  80.          T IReversibleGetResourceData<T>.GetNextData()  
  81.          {  
  82.              T result = new T();  
  83.              (_copy as IResourceCopy<T>).Copy(result, _commitfrontvalue);  
  84.              return result;  
  85.          }  
  86.          #endregion  
  87.      }  
  88.  } 

#p#

2.2可逆框架的入口实现

我们需要简单的调用就能方便的使用可逆功能,不能以一种新的方式使用。所以这里借鉴了Transaction Scope的设计思想。

请看代码:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.  using System.Transactions;  
  10.    
  11.  namespace ReversibleLib  
  12.  {  
  13.      /// <summary>  
  14.      /// 使代码成为可逆框架的事务性代码  
  15.      /// </summary>  
  16.      public class ReversibleManagerScope : IDisposable  
  17.      {  
  18.          /// <summary>  
  19.          /// 初始化ReversibleManagerScope新的实例  
  20.          /// </summary>  
  21.          public ReversibleManagerScope()  
  22.          {  
  23.              ReversibleManager._reversibleManager = new ReversibleManager();  
  24.          }  
  25.          /// <summary>  
  26.          /// 使用ReversibleManager对象构造ReversibleManagerScope使用范围对象  
  27.          /// </summary>  
  28.          /// <param name="manager">ReversibleManager实例</param>  
  29.          public ReversibleManagerScope(ReversibleManager manager)  
  30.          {  
  31.              ReversibleManager._reversibleManager = manager;  
  32.          }  
  33.          /// <summary>  
  34.          /// 使用自定义资源管理器构造ReversibleManagerScope包装的环境ReversibleManager.Current中的对象实例。  
  35.          /// </summary>  
  36.          /// <param name="source">IEnlistmentNotification资源管理器</param>  
  37.          public ReversibleManagerScope(IEnlistmentNotification source)  
  38.          {  
  39.              ReversibleManager._reversibleManager = new ReversibleManager(source);  
  40.          }  
  41.          /// <summary>  
  42.          /// 全局上下文ReversibleManager对象销毁  
  43.          /// </summary>  
  44.          public void Dispose()  
  45.          {  
  46.              ReversibleManager._reversibleManager = null;  
  47.          }  
  48.          /// <summary>  
  49.          /// 完成整个操作的提交。该操作将提交事务栈中的所有依赖事务  
  50.          /// </summary>  
  51.          public void Completed()  
  52.          {  
  53.              ReversibleManager.Current.Commit();  
  54.          }  
  55.      }  
  56.      /// <summary>  
  57.      /// 可逆模块的入口。  
  58.      /// ReversibleManager对事务对象的封装,实现阶段性的事务提交和回滚。  
  59.      /// </summary>  
  60.      public class ReversibleManager  
  61.      {  
  62.          #region 上下文静态ReversibleManager实例  
  63.          /// <summary>  
  64.          /// 持有对可逆框架的对象引用  
  65.          /// </summary>  
  66.          internal static ReversibleManager _reversibleManager;  
  67.          /// <summary>  
  68.          /// 获取当前上下文中可逆框架  
  69.          /// </summary>  
  70.          public static ReversibleManager Current  
  71.          {  
  72.              get { return _reversibleManager; }  
  73.          }  
  74.          #endregion  
  75.    
  76.          #region 构造对象  
  77.          /// <summary>  
  78.          /// 默认构造函数  
  79.          /// </summary>  
  80.          public ReversibleManager() { }  
  81.          /// <summary>  
  82.          /// 表示可提交的事务(主事务)  
  83.          /// </summary>  
  84.          private CommittableTransaction _commiTransaction;  
  85.          /// <summary>  
  86.          /// 支持两阶段提交协议的资源管理器(主资源管理器)  
  87.          /// </summary>  
  88.          private IEnlistmentNotification _resourceManager;  
  89.          /// <summary>  
  90.          /// 重载构造函数,使用自定义资源管理器构造可逆模块的开始。  
  91.          /// </summary>  
  92.          /// <param name="resource">IEnlistmentNotification接口对象</param>  
  93.          public ReversibleManager(IEnlistmentNotification resource)  
  94.          {  
  95.              _resourceManager = resource;  
  96.              InitLoad(IsolationLevel.Serializable);  
  97.          }  
  98.          /// <summary>  
  99.          /// 重载构造函数,使用自定义资源管理器、内部事务范围的事务隔离级别构造可逆模型的开始。  
  100.          /// </summary>  
  101.          /// <param name="resource">IEnlistmentNotification接口对象</param>  
  102.          /// <param name="isolationlevel">IsolationLevel枚举成员</param>  
  103.          public ReversibleManager(IEnlistmentNotification resource, IsolationLevel isolationlevel)  
  104.          {  
  105.              _resourceManager = resource;  
  106.              InitLoad(isolationlevel);  
  107.          }  
  108.          /// <summary>  
  109.          /// 事务初始化阶段的参数对象  
  110.          /// </summary>  
  111.          TransactionOptions _options;  
  112.          /// <summary>  
  113.          /// 重载构造函数,使用自定义资源管理器、内部事务范围的事务隔离级别、事务超时时间范围构造可逆模块的开始。  
  114.          /// </summary>  
  115.          /// <param name="resource">IEnlistmentNotification接口对象</param>  
  116.          /// <param name="isolationlevel">IsolationLevel枚举成员</param>  
  117.          /// <param name="span">TimeSpan时间范围</param>  
  118.          public ReversibleManager(IEnlistmentNotification resource, IsolationLevel isolationlevel, TimeSpan span)  
  119.          {  
  120.              _options = new TransactionOptions();  
  121.              _options.Timeout = span;  
  122.              InitLoad(isolationlevel);  
  123.          }  
  124.          /// <summary>  
  125.          /// 构造CommittableTransaction对象实例。  
  126.          /// </summary>  
  127.          /// <param name="level">事务隔离级别</param>  
  128.          private void InitLoad(IsolationLevel level)  
  129.          {  
  130.              if (_options == null)  
  131.                  _options = new TransactionOptions();  
  132.              _options.IsolationLevel = level;  
  133.              _commiTransaction = new CommittableTransaction(_options);  
  134.              _commiTransaction.EnlistVolatile(_resourceManager, EnlistmentOptions.None);  
  135.              //作为事务栈的头开始整个可逆结构。  
  136.              _tranStack.Push(_commiTransaction);//压入事务栈  
  137.              _resourceStack.Push(_resourceManager);//压入资源栈  
  138.              //设置环境事务,让所有支持事务性感知框架的代码都能执行。  
  139.              Transaction.Current = _commiTransaction;  
  140.          }  
  141.          #endregion  
  142.    
  143.          /// <summary>  
  144.          /// 事务栈,依次存放事务。  
  145.          /// </summary>  
  146.          private System.Collections.Generic.Stack<Transaction> _tranStack = new Stack<Transaction>();  
  147.          /// <summary>  
  148.          /// 资源栈,依次存放事务使用的资源。  
  149.          /// </summary>  
  150.          private System.Collections.Generic.Stack<IEnlistmentNotification> _resourceStack = new Stack<IEnlistmentNotification>();  
  151.          /// <summary>  
  152.          /// 阶段性事件委托  
  153.          /// </summary>  
  154.          /// <param name="tran">Transaction环境事务</param>  
  155.          public delegate void PhaseHanlder(System.Transactions.Transaction tran);  
  156.          /// <summary>  
  157.          /// 下一步事件  
  158.          /// </summary>  
  159.          public event PhaseHanlder NextEvent;  
  160.          /// <summary>  
  161.          /// 上一步事件  
  162.          /// </summary>  
  163.          public event PhaseHanlder PreviousEvent;  
  164.          /// <summary>  
  165.          /// 开始下一步操作  
  166.          /// </summary>  
  167.          /// <typeparam name="S">IEnlistmentNotification接口实现</typeparam>  
  168.          /// <param name="level">IsolationLevel事务的隔离级别(对全局事务处理设置)</param>  
  169.          /// <param name="source">下一步操作的自定义数据管理器</param>  
  170.          public void Next<S>(IsolationLevel level, S source)  
  171.              where S : class,IEnlistmentNotification, new()  
  172.          {  
  173.              Transaction tran = _tranStack.Peek();//获取事务栈的顶端事务  
  174.              if (tran == null)  
  175.                  tran = Transaction.Current;//主事务  
  176.              DependentTransaction depentran = tran.DependentClone(DependentCloneOption.BlockCommitUntilComplete);  
  177.              //将本次事务处理的资源管理器压入资源栈中  
  178.              depentran.EnlistVolatile(source, EnlistmentOptions.None);  
  179.              _tranStack.Push(depentran);  
  180.              _resourceStack.Push(source);  
  181.              //切换环境事务场景  
  182.              Transaction.Current = depentran;  
  183.              if (NextEvent != null)  
  184.                  if (NextEvent.GetInvocationList().Length > 0)  
  185.                      NextEvent(Transaction.Current);  
  186.          }  
  187.          /// <summary>  
  188.          /// 返回上一步操作  
  189.          /// </summary>  
  190.          /// <typeparam name="T">需要接受的数据对象类型</typeparam>  
  191.          /// <param name="refadd">需要接受的数据对象引用</param>  
  192.          public void Previous<T>(out T refadd) where T : class,new()  
  193.          {  
  194.              Transaction tran = _tranStack.Pop();  
  195.              if (tran == null)//顶层事务  
  196.                  Transaction.Current.Rollback();  
  197.              // tran.Rollback();//回滚本事务,将触发所有克隆事务的回滚。  
  198.              if (PreviousEvent != null)  
  199.                  if (PreviousEvent.GetInvocationList().Length > 0)  
  200.                  {  
  201.                      //设置上一步数据对象  
  202.                      refadd = (_resourceStack.Pop() as IReversibleGetResourceData<T>).GetPreviousData();  
  203.                      PreviousEvent(Transaction.Current);  
  204.                      return;  
  205.                  }  
  206.              refadd = new T();//事务处理异常  
  207.          }  
  208.          /// <summary>  
  209.          /// 提交事物堆栈中的所有事物  
  210.          /// </summary>  
  211.          public void Commit()  
  212.          {  
  213.              if (Transaction.Current is DependentTransaction)  
  214.                  (Transaction.Current as DependentTransaction).Complete();  
  215.              for (int i = 0; i < _tranStack.Count - 1; i++)  
  216.              {  
  217.                  //依赖事务  
  218.                  (_tranStack.Pop() as DependentTransaction).Complete();  
  219.              }  
  220.              //提交事务,主事务。必须进行克隆主体的提交才能完成所有阶段的操作。  
  221.              (_tranStack.Pop() as CommittableTransaction).Commit();  
  222.          }  
  223.          /// <summary>  
  224.          /// 回滚事物堆栈中的所有事物  
  225.          /// </summary>  
  226.          public void RollBack()  
  227.          {  
  228.              if (Transaction.Current is DependentTransaction)  
  229.                  (Transaction.Current as DependentTransaction).Rollback();  
  230.              for (int i = 0; i < _tranStack.Count - 1; i++)  
  231.              {  
  232.                  //依赖事务  
  233.                  (_tranStack.Pop() as DependentTransaction).Rollback();  
  234.              }  
  235.              //提交事务,主事务。必须进行克隆主体的提交才能完成所有阶段的操作。  
  236.              (_tranStack.Pop() as CommittableTransaction).Rollback();  
  237.          }  
  238.      }  
  239.  } 

3.示例

这里我使用了一个简单的String Builder作为资源管理器需要管理的对象。

请看代码:

  1. View Code   
  2.  /***  
  3.   * author:深度训练  
  4.   * blog:http://wangqingpei557.blog.51cto.com/  
  5.   * **/ 
  6.  using System;  
  7.  using System.Collections.Generic;  
  8.  using System.Text;  
  9.  using System.Data;  
  10.  using System.Transactions;  
  11.  using ReversibleLib;  
  12.    
  13.  namespace ConsoleApplication1  
  14.  {  
  15.      class Program  
  16.      {  
  17.          static void Main(string[] args)  
  18.          {  
  19.              //构造数据  
  20.              StringBuilder strbuilder = new StringBuilder();  
  21.              strbuilder.Append("0");//初始数据为0  
  22.    
  23.              //资源管理器  
  24.              ReResourceManager<StringBuilder, StringBuilderCopy> strResource =  
  25.                  new ReResourceManager<StringBuilder, StringBuilderCopy>(strbuilder, new StringBuilderCopy());  
  26.              strResource.Name = "0资源管理器";  
  27.              //开始进入可逆框架处理环境  
  28.              using (ReversibleManagerScope reversible = new ReversibleManagerScope(strResource))  
  29.              {  
  30.                  try 
  31.                  {  
  32.                      ReversibleManager.Current.PreviousEvent += new ReversibleManager.PhaseHanlder(Current_PreviousEvent);  
  33.                      ReversibleManager.Current.NextEvent += new ReversibleManager.PhaseHanlder(Current_NextEvent);  
  34.                      strbuilder.Append("1");//首次修改数据为01  
  35.    
  36.                      //获取下一步操作的数据  
  37.                      StringBuilder strbuilder2 = (strResource as IReversibleGetResourceData<StringBuilder>).GetNextData();  
  38.                      //构造下一步操作的自定义资源管理器  
  39.                      ReResourceManager<StringBuilder, StringBuilderCopy> strResource2 =  
  40.                          new ReResourceManager<StringBuilder, StringBuilderCopy>(strbuilder2, new StringBuilderCopy());  
  41.                      strResource2.Name = "2资源管理器";  
  42.                      ReversibleManager.Current.Next<ReResourceManager<StringBuilder, StringBuilderCopy>>(  
  43.                          System.Transactions.IsolationLevel.Serializable, strResource2);  
  44.                      strbuilder2.Append("2");//第二步修改数据为012  
  45.    
  46.                      //返回上一步,也就是回滚对数据进行“2”设置的前一个状态  
  47.                      StringBuilder strbuilder3;  
  48.                      ReversibleManager.Current.Previous<StringBuilder>(out strbuilder3);//获取上一步使用的数据,这里应该是01  
  49.    
  50.                      reversible.Completed();//提交所有操作  
  51.                      Console.WriteLine(strbuilder3);  
  52.                  }  
  53.                  catch (Exception err)  
  54.                  { Console.WriteLine(err.Message); ReversibleManager.Current.RollBack(); }  
  55.              }  
  56.              Console.ReadLine();  
  57.          }  
  58.    
  59.          static void Current_NextEvent(Transaction tran)  
  60.          {  
  61.              Console.WriteLine("下一步:" + tran.TransactionInformation.LocalIdentifier);  
  62.              Console.WriteLine("下一步:" + tran.TransactionInformation.DistributedIdentifier);  
  63.          }  
  64.          static void Current_PreviousEvent(Transaction tran)  
  65.          {  
  66.              Console.WriteLine("上一步:" + tran.TransactionInformation.LocalIdentifier);  
  67.              Console.WriteLine("上一步:" + tran.TransactionInformation.DistributedIdentifier);  
  68.          }  
  69.      }  
  70.  } 

这里我使用0作为资源的初始数据,然后进入到第一个环节,我将它附加了1,然后进入到第二个环节,我将它附加了2,这里应该是012了,但是下面我突然又返回到了上一步,所以最后的数据应该是01。如果我们需要使用复杂的数据对象,如常用的Data Table类型,我们一般都是用它来展现一组数据,然后对这组数据进行一系列的操作。

总结:

这篇文章主要是想介绍一下事务的另一种使用方式,对可逆框架的设计方向算是一个抛砖引玉吧,希望大家用的着。

源码地址:http://files.cnblogs.com/wangiqngpei557/Reversible.zip

原文链接:http://www.cnblogs.com/wangiqngpei557/archive/2012/06/24/2560576.html

责任编辑:林师授 来源: 博客园
相关推荐

2012-06-25 09:28:42

.NET可逆框架

2016-03-23 11:05:58

Socket开发框架分析

2012-01-18 10:20:42

框架设计

2009-09-08 09:12:12

LINQ构建框架设计

2020-07-30 10:35:32

Java反射框架设计

2012-01-10 10:04:43

Node.js

2010-09-25 13:09:39

UISymbian

2021-02-23 08:18:04

Java 反射机制

2011-04-22 09:26:57

MVC设计

2022-06-15 11:01:59

自定义SPIJava

2022-10-10 09:11:12

互联网存储系统云计算

2022-09-15 18:32:13

SPI模型框架

2022-09-25 21:45:54

日志平台

2017-04-12 23:33:38

DevOps平衡计分卡框架

2022-04-03 15:44:55

Vue.js框架设计设计与实现

2014-09-23 10:05:55

2013-09-09 10:48:24

iOS无线客户端框架设计

2013-09-03 09:35:48

无线客户端框架设计iOS

2013-09-03 09:55:42

iOS无线客户端框架设计

2022-12-16 12:16:21

点赞
收藏

51CTO技术栈公众号