现在的位置: 首页 > 综合 > 正文

petshop4.0 详解之三(PetShop数据访问层之消息处理)

2014年02月05日 ⁄ 综合 ⁄ 共 7969字 ⁄ 字号 评论关闭
在进行系统设计时,除了对安全、事务等问题给与足够的重视外,性能也是一个不可避免的问题所在,尤其是一个B/S结构的软件系统,必须充分地考虑访问量、数据流量、服务器负荷的问题。解决性能的瓶颈,除了对硬件系统进行升级外,软件设计的合理性尤为重要。
在前面我曾提到,分层式结构设计可能会在一定程度上影响数据访问的性能,然而与它给设计人员带来的好处相比,几乎可以忽略。要提供整个系统的性能,还可以从数据库的优化着手,例如连接池的使用、建立索引、优化查询策略等等,例如在PetShop中就利用了数据库的Cache,对于数据量较大的订单数据,则利用分库的方式为其单独建立了Order和Inventory数据库。而在软件设计上,比较有用的方式是利用多线程与异步处理方式。
在PetShop4.0中,使用了Microsoft Messaging Queue(MSMQ)技术来完成异步处理,利用消息队列临时存放要插入的数据,使得数据访问因为不需要访问数据库从而提供了访问性能,至于队列中的数据,则等待系统空闲的时候再进行处理,将其最终插入到数据库中。
PetShop4.0中的消息处理,主要分为如下几部分:消息接口IMessaging、消息工厂MessagingFactory、MSMQ实现MSMQMessaging以及数据后台处理应用程序OrderProcessor。
从模块化分上,PetShop自始自终地履行了“面向接口设计”的原则,将消息处理的接口与实现分开,并通过工厂模式封装消息实现对象的创建,以达到松散耦合的目的。
由于在PetShop中仅对订单的处理使用了异步处理方式,因此在消息接口IMessaging中,仅定义了一个IOrder接口,其类图如下:
 

在对消息接口的实现中,考虑到未来的扩展中会有其他的数据对象会使用MSMQ,因此定义了一个Queue的基类,实现消息Receive和Send的基本操作:

  1. public virtual object Receive() 
  2. {
  3.       try 
  4. {
  5.           using (Message message = queue.Receive(timeout, transactionType))
  6.              return message;
  7.       }
  8.       catch (MessageQueueException mqex) 
  9. {
  10.           if (mqex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
  11.              throw new TimeoutException();
  12.                 throw;
  13.       }
  14. }
  15. public virtual void Send(object msg) 
  16. {
  17.       queue.Send(msg, transactionType);
  18. }

其中queue对象是System.Messaging.MessageQueue类型,作为存放数据的队列。MSMQ队列是一个可持久的队列,因此不必担心用户不间断地下订单会导致订单数据的丢失。在PetShopQueue设置了timeout值,OrderProcessor会根据timeout值定期扫描队列中的订单数据。
MSMQMessaging模块中,Order对象实现了IMessaging模块中定义的接口IOrder,同时它还继承了基类PetShopQueue,其定义如下:
public class order:PetShopQueue, PetShop.IMessaging.IOrder
方法的实现代码如下:

  1. public new orderInfo Receive() 
  2.     {
  3.         // This method involves in distributed transaction and need Automatic Transaction type
  4.         base.transactionType = MessageQueueTransactionType.Automatic;
  5.         return (OrderInfo)((Message)base.Receive()).Body;
  6.     } 
  7.     public orderInfo Receive(int timeout) 
  8.     {
  9.         base.timeout = TimeSpan.FromSeconds(Convert.ToDouble(timeout));
  10.         return Receive();
  11.     }
  12.     public void Send(OrderInfo orderMessage) 
  13.     {
  14.         // This method does not involve in distributed transaction and optimizes performance using Single type
  15.         base.transactionType = MessageQueueTransactionType.Single;
  16.         base.Send(orderMessage);
  17.     }

所以,最后的类图应该如下:
 

注意在Order类的Receive()方法中,是用new关键字而不是override关键字来重写其父类PetShopQueue的Receive()虚方法。因此,如果是实例化如下的对象,将会调用PetShopQueue的Receive()方法,而不是子类Order的Receive()方法:
PetShopQueue queue = new order();
queue.Receive();
从设计上来看,由于PetShop采用“面向接口设计”的原则,如果我们要创建Order对象,应该采用如下的方式:
IOrder order = new order();
order.Receive();
考虑到IOrder的实现有可能的变化,PetShop仍然利用了工厂模式,将IOrder对象的创建用专门的工厂模块进行了封装:
 

在类QueueAccess中,通过CreateOrder()方法利用反射技术创建正确的IOrder类型对象:

  1. public static PetShop.IMessaging.IOrder CreateOrder() 
  2.     {
  3.         string className = path + ".Order";
  4.         return PetShop.IMessaging.IOrder)Assembly.Load(path).CreateInstance(className);
  5.     }

path的值通过配置文件获取:

  1. private static readonly string path = ConfigurationManager.AppSettings["OrderMessaging"];

而配置文件中,OrderMessaging的值设置如下:
<add key="OrderMessaging" value="PetShop.MSMQMessaging"/>
之所以利用工厂模式来负责对象的创建,是便于在业务层中对其调用,例如在BLL模块中OrderAsynchronous类:

  1. public class orderAsynchronous : IOrderStrategy
  2. {        
  3.     private static readonly PetShop.IMessaging.IOrder asynchOrder = PetShop.MessagingFactory.QueueAccess.CreateOrder();
  4.     public void Insert(PetShop.Model.OrderInfo order) 
  5. {
  6.         asynchOrder.Send(order);
  7.     }
  8. }

一旦IOrder接口的实现发生变化,这种实现方式就可以使得客户仅需要修改配置文件,而不需要修改代码,如此就可以避免程序集的重新编译和部署,使得系统能够灵活应对需求的改变。例如定义一个实现IOrder接口的SpecialOrder,则可以新增一个模块,如PetShop.SpecialMSMQMessaging,而类名则仍然为Order,那么此时我们仅需要修改配置文件中OrderMessaging的值即可:
<add key="OrderMessaging" value="PetShop.SpecialMSMQMessaging"/>
OrderProcessor是一个控制台应用程序,不过可以根据需求将其设计为Windows Service。它的目的就是接收消息队列中的订单数据,然后将其插入到Order和Inventory数据库中。它利用了多线程技术,以达到提高系统性能的目的。
在OrderProcessor应用程序中,主函数Main用于控制线程,而核心的执行任务则由方法ProcessOrders()实现:

  1.  private static void ProcessOrders() 
  2.     {
  3.         // the transaction timeout should be long enough to handle all of orders in the batch
  4.         TimeSpan tsTimeout = TimeSpan.FromSeconds(Convert.ToDouble(transactionTimeout * batchSize));
  5.         order order = new order();
  6.         while (true
  7.         {
  8.             // queue timeout variables
  9.             TimeSpan datetimeStarting = new TimeSpan(DateTime.Now.Ticks);
  10.             double elapsedTime = 0;
  11.             int processedItems = 0;
  12.             ArrayList queueOrders = new ArrayList();
  13.             using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, tsTimeout)) 
  14.             {
  15.                 // Receive the orders from the queue
  16.                 for (int j = 0; j < batchSize; j++) 
  17.                 {
  18.                     try 
  19.                     {
  20.                         //only receive more queued orders if there is enough time
  21.                         if ((elapsedTime + queueTimeout + transactionTimeout) < tsTimeout.TotalSeconds)
  22.                         {
  23.                             queueOrders.Add(order.ReceiveFromQueue(queueTimeout));
  24.                         }
  25.                         else 
  26.                         {
  27.                             j = batchSize;   // exit loop
  28.                         }
  29.                         //update elapsed time
  30.                         elapsedTime = new TimeSpan(DateTime.Now.Ticks).TotalSeconds - datetimeStarting.TotalSeconds;
  31.                     }
  32.                     catch (TimeoutException) 
  33.                     {
  34.                         //exit loop because no more messages are waiting
  35.                         j = batchSize;
  36.                     }
  37.                 }
  38.                 //process the queued orders
  39.                 for (int k = 0; k < queueOrders.Count; k++) 
  40.                 {
  41.                     order.Insert((OrderInfo)queueOrders[k]);
  42.                     processedItems++;
  43.                     totalOrdersProcessed++;
  44.                 }
  45.                 //batch complete or MSMQ receive timed out
  46.                 ts.Complete();
  47.             }
  48.             Console.WriteLine("(Thread Id " + Thread.CurrentThread.ManagedThreadId + ") batch finished, " + processedItems + " items, in " + elapsedTime.ToString() + " seconds.");
  49.         }
  50.     }

  首先,它会通过PetShop.BLL.Order类的公共方法ReceiveFromQueue()来获取消息队列中的订单数据,并将其放入到一个ArrayList对象中,然而再调用PetShop.BLL.Order类的Insert方法将其插入到Order和Inventory数据库中。
在PetShop.BLL.Order类中,并不是直接执行插入订单的操作,而是调用了IOrderStrategy接口的Insert()方法:

  1. public void Insert(OrderInfo order) 
  2. {
  3.     // Call credit card procesor
  4.     ProcessCreditCard(order);
  5.     // Insert the order (a)synchrounously based on configuration
  6.     orderInsertStrategy.Insert(order);
  7. }

在这里,运用了一个策略模式,类图如下所示:
 

在PetShop.BLL.Order类中,仍然利用配置文件来动态创建IOrderStategy对象:

  1. private static readonly PetShop.IBLLStrategy.IOrderStrategy orderInsertStrategy = LoadInsertStrategy();
  2. private static PetShop.IBLLStrategy.IOrderStrategy LoadInsertStrategy() 
  3. {
  4.     // Look up which strategy to use from config file
  5.     string path = ConfigurationManager.AppSettings["OrderStrategyAssembly"];
  6.     string className = ConfigurationManager.AppSettings["OrderStrategyClass"];
  7.     // Using the evidence given in the config file load the appropriate assembly and class
  8.     return (PetShop.IBLLStrategy.IOrderStrategy)Assembly.Load(path).CreateInstance(className);
  9. }

由于OrderProcessor是一个单独的应用程序,因此它使用的配置文件与PetShop不同,是存放在应用程序的App.config文件中,在该文件中,对IOrderStategy的配置为:
<add key="OrderStrategyAssembly" value="PetShop.BLL" />
<add key="OrderStrategyClass" value="PetShop.BLL.OrderSynchronous" />
因此,以异步方式插入订单的流程如下图所示:
 

Microsoft Messaging Queue(MSMQ)技术除用于异步处理以外,它主要还是一种分布式处理技术。分布式处理中,一个重要的技术要素就是有关消息的处理,而在System.Messaging命名空间中,已经提供了Message类,可以用于承载消息的传递,前提上消息的发送方与接收方在数据定义上应有统一的接口规范。
MSMQ在分布式处理的运用,在我参与的项目中已经有了实现。在为一个汽车制造商开发一个大型系统时,分销商Dealer作为.Net客户端,需要将数据传递到管理中心,并且该数据将被Oracle的EBS(E-Business System)使用。由于分销商管理系统(DMS)采用的是C/S结构,数据库为SQL Server,而汽车制造商管理中心的EBS数据库为Oracle。这里就涉及到两个系统之间数据的传递。
实现架构如下:

     首先Dealer的数据通过MSMQ传递到MSMQ Server,此时可以将数据插入到SQL Server数据库中,同时利用FTP将数据传送到专门的文件服务器上。然后利用IBM的EAI技术(企业应用集成,Enterprise Application Itegration)定期将文件服务器中的文件,利用接口规范写入到EAI数据库服务器中,并最终写道EBS的Oracle数据库中。
上述架构是一个典型的分布式处理结构,而技术实现的核心就是MSMQ和EAI。由于我们已经定义了统一的接口规范,在通过消息队列形成文件后,此时的数据就已经与平台无关了,使得在.Net平台下的分销商管理系统能够与Oracle的EBS集成起来,完成数据的处理。

抱歉!评论已关闭.