当前位置: 移动技术网 > IT编程>开发语言>.net > 仅此一文让你明白事务隔离级别、脏读、不可重复读、幻读

仅此一文让你明白事务隔离级别、脏读、不可重复读、幻读

2019年02月26日  | 移动技术网IT编程  | 我要评论

甲醛除味,渝简称,黑莓概念机

网络上关于这方面的博文有些偏理论,有些通篇代码,都不能深入浅出。本文用图文并茂的方式,配上行云流水般的代码,非要摆清楚这个问题。相关代码已提交至码云(点击这里下载)。

事务是现代关系型数据库的核心之一。在多个事务并发操作数据库(多线程、网络并发等)的时候,如果没有有效的避免机制,就会出现以下几种问题:

第一类丢失更新(lost update)

在完全未隔离事务的情况下,两个事务更新同一条数据资源,某一事务完成,另一事务异常终止,回滚造成第一个完成的更新也同时丢失 。这个问题现代关系型数据库已经不会发生,就不在这里占用篇幅,有兴趣的可以自行百度。

脏读(dirty read)

a事务执行过程中,b事务读取了a事务的修改。但是由于某些原因,a事务可能没有完成提交,发生rollback了操作,则b事务所读取的数据就会是不正确的。这个未提交数据就是脏读(dirty read)。脏读产生的流程如下:

可以用ef core模拟此过程:

    class testreaduncommitted :testbase
    {
        private autoresetevent _autoresetevent;

        [test]
        public void readuncommitted()
        {
            using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
            {
                var user = context.users.singleordefault(u => u.account == "admin");
                console.writeline($"初始用户状态:【{user.status}】");
            }

            _autoresetevent = new autoresetevent(false);
            threadpool.queueuserworkitem(data =>{
                write();  //启动线程写
            });
            threadpool.queueuserworkitem(data =>{
                read();  //启动线程读
            });

            thread.sleep(5000);

            using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
            {
                var user = context.users.singleordefault(u => u.account == "admin");
                console.writeline($"最终用户状态:【{user.status}】");
            }
        }

        private void read()
        {
            _autoresetevent.waitone();

            var options = new transactionoptions { isolationlevel = isolationlevel.readuncommitted };
            using (var scope = new transactionscope(transactionscopeoption.required, options))
            {
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    var user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务b:脏读到的用户状态:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                    //如果这时执行下面的判断
                    if (user.status == 1)
                    {
                        console.writeline("事务b:非正常数据,会产生意想不到的bug");
                    }
                }
            }
        }
        private void write()
        {
            using (var scope = new transactionscope(transactionscopeoption.required,
                new transactionoptions {isolationlevel = isolationlevel.readcommitted}))
            {
                console.writeline($"事务a:修改--{datetime.now.tostring("hh:mm:ss fff")}");
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    var user = context.users.singleordefault(u => u.account == "admin");
                    user.status = 1-user.status;  //模拟修改
                    context.savechanges();
                }

                _autoresetevent.set();  //模拟多线程切换,这时切换到read线程,复现脏读

                thread.sleep(2000);  //模拟长事务
                console.writeline($"事务a:改完,但没提交--{datetime.now.tostring("hh:mm:ss fff")}");
            }
        }
    }
脏读示例

对应的执行结果:

不可重复读(nonrepeatable read)

b事务读取了两次数据,在这两次的读取过程中a事务修改了数据,b事务的这两次读取出来的数据不一样。b事务这种读取的结果,即为不可重复读(nonrepeatable read)。不可重复读的产生的流程如下:

微信截图_20190223004632

模拟代码如下:

public class testreadcommitted : testbase
    {
        private autoresetevent _towriteevent = new autoresetevent(false);
        private autoresetevent _toreadevent = new autoresetevent(false);

        [test]
        public void readcommitted()
        {
            threadpool.queueuserworkitem(data => {
                read();  //启动线程读
            });
            threadpool.queueuserworkitem(data => {
                write();  //启动线程写
            });

            thread.sleep(5000);

            using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
            {
                var user = context.users.singleordefault(u => u.account == "admin");
                console.writeline($"最终用户状态:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
            }

        }

        private void read()
        {
            using (var transactionscope = new transactionscope(transactionscopeoption.required,
                new transactionoptions { isolationlevel = isolationlevel.readcommitted }))
            {
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    var user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务b:第一次读取:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                }

                _towriteevent.set();  //模拟多线程切换,这时切换到写线程,复现不可重复读
                _toreadevent.waitone();

                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    var user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务b:第二次读取:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                }
            }

        }

        private void write()
        {
            _towriteevent.waitone();

            using (var scope = new transactionscope(transactionscopeoption.required,
                new transactionoptions { isolationlevel = isolationlevel.readcommitted }))
            {
                user user = null;
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务a:读取为【{user?.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                    user.status = 1 - user.status;
                    context.savechanges();
                }
                scope.complete();
                console.writeline($"事务a:已被更改为【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                _toreadevent.set();
            }
        }
    }
不可重复读示例

对应的执行结果:

不可重复读有一种特殊情况,两个事务更新同一条数据资源,后完成的事务会造成先完成的事务更新丢失。这种情况就是大名鼎鼎的第二类丢失更新。主流的数据库已经默认屏蔽了第一类丢失更新问题(即:后做的事务撤销,发生回滚造成已完成事务的更新丢失),但我们编程的时候仍需要特别注意第二类丢失更新。它产生的流程如下:

模拟代码如下:

public class testreadcommitted2 : testbase
    {
        private autoresetevent _towriteevent = new autoresetevent(false);
        private autoresetevent _toreadevent = new autoresetevent(false);

        [test]
        public void readcommitted()
        {
            threadpool.queueuserworkitem(data => {
                read();  //启动线程读
            });
            threadpool.queueuserworkitem(data => {
                write();  //启动线程写
            });

            thread.sleep(5000);

            using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
            {
                var user = context.users.singleordefault(u => u.account == "admin");
                console.writeline($"最终用户状态:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
            }
        }

        private void read()
        {
            using (var transactionscope = new transactionscope(transactionscopeoption.required,
                new transactionoptions { isolationlevel = isolationlevel.readcommitted }))
            {
                user user = null;
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务b:第一次读取:【{user?.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                }

                _towriteevent.set();  //模拟多线程切换,这时切换到写线程,复现不可重复读
                _toreadevent.waitone();

                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务b:第二次读取:【{user?.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                    user.status = 1 - user.status;
                    context.savechanges();
                }
                transactionscope.complete();
                console.writeline($"事务b:已被更改为【{user?.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
            }

        }

        private void write()
        {
            _towriteevent.waitone();

            using (var scope = new transactionscope(transactionscopeoption.required,
                new transactionoptions { isolationlevel = isolationlevel.readcommitted }))
            {
                user user = null;
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务a:读取为【{user?.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                    user.status = 1 - user.status;
                    context.savechanges();
                }
                scope.complete();
                console.writeline($"事务a:已被更改为【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                _toreadevent.set();
            }
        }
    }
第二类更新丢失示例

对应的执行结果如下图:

可以明显看出事务a的更新被事务b所覆盖,更新丢失。

幻读(phantom read)

b事务读取了两次数据,在这两次的读取过程中a事务添加了数据,b事务的这两次读取出来的集合不一样。幻读产生的流程如下:

这个流程看起来和不可重复读差不多,但幻读强调的集合的增减,而不是单独一条数据的修改。

模拟代码如下:

public class testrepeat : testbase
    {
        private autoresetevent _towriteevent = new autoresetevent(false);
        private autoresetevent _toreadevent = new autoresetevent(false);

        [test]
        public void repeat()
        {
            threadpool.queueuserworkitem(data => {
                read();  //启动线程读
            });
            threadpool.queueuserworkitem(data => {
                write();  //启动线程写
            });

            thread.sleep(6000);

        }

        private void read()
        {
            using (var transactionscope = new transactionscope(transactionscopeoption.required,
                new transactionoptions { isolationlevel = isolationlevel.repeatableread }))
            {
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    console.writeline($"事务b:第一次读取:【{context.users.count()}】--{datetime.now.tostring("hh:mm:ss fff")}");
                }

                _towriteevent.set();  //模拟多线程切换,这时切换到写线程,复现幻读
                _toreadevent.waitone();

                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    console.writeline($"事务b:第二次读取:【{context.users.count()}】--{datetime.now.tostring("hh:mm:ss fff")}");
                }
            }

        }

        private void write()
        {
            _towriteevent.waitone();

            using (var scope = new transactionscope(transactionscopeoption.required,
                     new transactionoptions { isolationlevel = isolationlevel.readcommitted }))
            {
                console.writeline($"事务a:新增一条--{datetime.now.tostring("hh:mm:ss fff")}");
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    var id = generateid.shortstr();
                    context.users.add(new user { id = id, account = id, status = 0, name = id, createtime = datetime.now});
                    context.savechanges();
                }
                scope.complete();
                console.writeline($"事务a:完成新增--{datetime.now.tostring("hh:mm:ss fff")}");
                _toreadevent.set();
            }
        }
    }
幻读示例

执行结果:

数据库隔离级别

为了解决上面提及的并发问题,主流关系型数据库都会提供四种事务隔离级别。

读未提交(read uncommitted)

在该隔离级别,所有事务都可以看到其他未提交事务的执行结果。本隔离级别是最低的隔离级别,虽然拥有超高的并发处理能力及很低的系统开销,但很少用于实际应用。因为采用这种隔离级别只能防止第一类更新丢失问题,不能解决脏读,不可重复读及幻读问题。

读已提交(read committed)

这是大多数数据库系统的默认隔离级别(但不是mysql默认的)。它满足了隔离的简单定义:一个事务只能看见已经提交事务所做的改变。这种隔离级别可以防止脏读问题,但会出现不可重复读及幻读问题。

可重复读(repeatable read)

这是mysql的默认事务隔离级别,它确保同一事务的多个实例在并发读取数据时,会看到同样的数据行。这种隔离级别可以防止除幻读外的其他问题。

可串行化(serializable)

这是最高的隔离级别,它通过强制事务排序,使之不可能相互冲突,从而解决幻读、第二类更新丢失问题。在这个级别,可以解决上面提到的所有并发问题,但可能导致大量的超时现象和锁竞争,通常数据库不会用这个隔离级别,我们需要其他的机制来解决这些问题:乐观锁和悲观锁。

这四种隔离级别会产生的问题如下(网上到处都有,懒得画了):

如何使用数据库的隔离级别

很多文章博客在介绍完这些隔离级别以后,就没有以后了。读的人一般会觉得,嗯,是这么回事,我知道了!

学习一个知识点,是需要实践的。比如下面这个常见而又异常严重的情况:

图中是典型的第二类丢失更新问题,后果异常严重。我们这里就以读已提交(read committed)及以下隔离级别中会出现不可重复读现象为例。从上面的表格可以看出,当事务隔离级别为可重复读(repeatable read)时可以避免。把testreadcommitted中的read线程事务级别调整一下:

////////////////////////////////////////////////////////////////////////////////////////////////////
// file:	test\testreadcommitted.cs
//
// summary:	读已提交会出现“不可重复读”现象
//              把读线程(事务b)的隔离级别调整到repeatableread,即可杜绝
////////////////////////////////////////////////////////////////////////////////////////////////////

using system;
using system.linq;
using system.threading;
using system.transactions;
using microsoft.entityframeworkcore;
using microsoft.extensions.dependencyinjection;
using nunit.framework;
using testtransaction.domain;

namespace testtransaction.test
{
    public class testreadcommitted : testbase
    {
        private autoresetevent _towriteevent = new autoresetevent(false);
        private autoresetevent _toreadevent = new autoresetevent(false);

        [test]
        public void readcommitted()
        {
            threadpool.queueuserworkitem(data => {
                read();  //启动线程读
            });
            threadpool.queueuserworkitem(data => {
                write();  //启动线程写
            });

            thread.sleep(60000);

            using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
            {
                var user = context.users.singleordefault(u => u.account == "admin");
                console.writeline($"最终用户状态:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
            }

        }

        private void read()
        {
            //读线程(事务b)的隔离级别调整到repeatableread
            using (var transactionscope = new transactionscope(transactionscopeoption.required,
                new transactionoptions { isolationlevel = isolationlevel.repeatableread, timeout = timespan.fromseconds(40) }))
            {
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    var user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务b:第一次读取:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                }

                _towriteevent.set();  //模拟多线程切换,这时切换到写线程,复现不可重复读
                _toreadevent.waitone();

                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    var user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务b:第二次读取:【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                }
            }

        }

        private void write()
        {
            _towriteevent.waitone();

            using (var scope = new transactionscope(transactionscopeoption.required,
                new transactionoptions { isolationlevel = isolationlevel.readcommitted, timeout = timespan.fromseconds(5) }))
            {
                user user = null;
                using (var context = _autofacserviceprovider.getservice<openauthdbcontext>())
                {
                    user = context.users.singleordefault(u => u.account == "admin");
                    console.writeline($"事务a:读取为【{user?.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                    user.status = 1 - user.status;
                    try
                    {
                        context.savechanges();
                        scope.complete();

                        console.writeline($"事务a:已被更改为【{user.status}】--{datetime.now.tostring("hh:mm:ss fff")}");
                    }
                    catch (dbupdateexception e)
                    {
                        console.writeline($"事务a:异常,为了保证可重复读,你的修改提交失败,请稍后重试--{datetime.now.tostring("hh:mm:ss fff")}");
                    }
                }
                _toreadevent.set();
            }
        }
    }
}

这时执行效果如下:

实际项目中,通过提示客户端重做的方式,完美解决了不可重复读的问题。其他并发问题,也可以通过类似的方式解决。

最后,文中提到可串行化解决幻读的问题,会在下篇文章详细介绍,包含各种酷炫的乐观锁操作,敬请期待!本文唯一访问地址:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网