ChatinCode

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

    在前一篇日志中,我阐述了使用单个Sql Server实例上的跨数据库事务引起的维护一致性难题。同时在日志末尾,又对跨数据库事务的实现提出了疑问(因为数据库的日志文件是隶属于数据库的,而不是全局的),经过查询,获知在同一Sql Server实例中的跨数据库事务实际上是分布式事务

    请看下面的MSDN摘录:

A transaction within a single instance of the Database Engine that spans two or more databases is actually a distributed transaction. The instance manages the distributed transaction internally; to the user, it operates as a local transaction

    注意,这里没有用到外部的MSDTC,Sql Server实例充当了分布事务管理器(或者叫事务协调器)的角色。对于客户程序,它看起来和非分布式的本地事务一样。同样,Sql Server使用著名的两阶段提交协议(2PC)来管理这种分布式事务。

    两阶段提交的两个阶段是这样的:

Prepare phase(准备阶段)

When the transaction manager receives a commit request, it sends a prepare command to all of the resource managers involved in the transaction. Each resource manager then does everything required to make the transaction durable, and all buffers holding log images for the transaction are flushed to disk. As each resource manager completes the prepare phase, it returns success or failure of the prepare to the transaction manager.

Commit phase(提交阶段)

If the transaction manager receives successful prepares from all of the resource managers, it sends commit commands to each resource manager. The resource managers can then complete the commit. If all of the resource managers report a successful commit, the transaction manager then sends a success notification to the application. If any resource manager reported a failure to prepare, the transaction manager sends a rollback command to each resource manager and indicates the failure of the commit to the application.

    问题在于提交阶段,假设牵涉数据库A和B的一个此种分布式事务,在提交阶段,也有可能事务中涉及A部分已经写入,而B部分写入失败。事务协调器也可能此时失效,数据库A可能无法回滚…个人感觉,仍然有各种复杂情况出现。

    所以鉴于跨数据库事务的复杂性,建议节约使用跨数据库事务,同一数据库中的跨架构(schema)事务是一个很好的替代。

    附:MSDN原文链接

    欢迎拍砖。

posted on 2011-11-11 14:24  ChatinCode  阅读(3014)  评论(0编辑  收藏  举报