Home > Database > Mysql Tutorial > body text

分布式事务原理及使用范例一则

WBOY
Release: 2016-06-07 16:06:44
Original
1023 people have browsed it

摘要:在软件开发和数据库操作中,经常出现需要共同进退的情况,要么一起成功,要么一起失败。 假设案例: A向B转账3000元rmb。 update Account set Amount=Amount-3000 where name=a update account set Amount=Amount+3000 where name=b 场景: 假设在第1

摘要:在软件开发和数据库操作中,经常出现需要共同进退的情况,要么一起成功,要么一起失败。

假设案例:A向B转账3000元rmb。 update Account set Amount=Amount-3000 where name='a' update account set Amount=Amount+3000 where name='b' 场景:假设在第1行代码执行成功,第2行代码还未执行的情况下。未继续执行。 结果:A的钱没了!B没收到钱!

此时推荐使用分布式事务来解决这类问题。

解决方案 应该实现原子性:要么全部成功、要么全部失败(回滚)
事务: 事务(Transaction)的特征是“原子性”,也就是“要么全部成功,要么全部失败”。事务实现还是有很多方法,最常见的就是使用链接相关SqlTransaction SqlTransaction 优点:1 不需要做客户端、服务器端的配置;2 无须启用事务协调服务(MSDTC) 缺点:无法实现分布式事务、嵌套事务、编写麻烦。
TransactionScope用来实现分布式事务(可以跨数据库、跨机器操作)的步骤 1 Windows服务中开启MSDTC(Distributed Transaction Coordinator),并且启动类型改为“自动”。注意:需要在ADO.NET端和数据库端上需要都进行相同操作。 2 项目添加对System.Transactions的引用 代码范例:
//包起来就会两者一起。一起成功,或者一起失败
using(TransactionScope ts=new TransactionScope())
{
    "update Account set Amount=Amount-3000 where name='a'";//从A账户扣钱的操作
    "update account set Amount=Amount+3000 where name='b'"//向B账户增加钱的操作
    ts.Complete();//忘记这句话,两个都插入失败
}
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!