多线程应用程序中出现SQLite“数据库被锁定”错误

clj7thdc  于 12个月前  发布在  SQLite
关注(0)|答案(3)|浏览(156)

有一个多线程应用程序,可处理大型DB文件(>600 Mb)。“数据库被锁定”的问题开始时,我添加了二进制大对象数据,并开始操作与>30 KB的二进制大对象数据每个请求。我认为问题与小硬盘速度。看起来像SQLite删除了-journal文件,我的应用程序的一个线程失去了锁定(因为-journal文件被应用并删除),另一个线程想用DB做smth,但SQLite仍然更新DB文件。当然,我可以在每次DB调用后延迟一分钟,但这不是一个解决方案,因为我需要更快的速度。
现在我使用会话每会话(每线程)实现。因此,每个应用程序对象和许多ISession对象都有一个ISessionFactory。
这里有我的助手类(正如你所看到的,我使用了IsolationLevel.Serializable和CurrentSessionContext = ThreadStaticSessionContext):

public abstract class nHibernateHelper
{
    private static FluentConfiguration _configuration;
    private static IPersistenceContext _persistenceContext;

    static nHibernateHelper() {}

    private static FluentConfiguration ConfigurePersistenceLayer()
    {
        return Fluently.Configure().Database(FluentNHibernate.Cfg.Db.SQLiteConfiguration.Standard.ShowSql().UsingFile(_fileName).IsolationLevel(IsolationLevel.Serializable).MaxFetchDepth(2)).
                Mappings(m => m.FluentMappings.AddFromAssemblyOf<Foo>()).CurrentSessionContext(typeof(ThreadStaticSessionContext).FullName);
    }

    public static ISession CurrentSession
    {
        get { return _persistenceContext.CurrentSession; }
    }

    public static IDisposable OpenConnection()
    {
        return new DbSession(_persistenceContext);
    }
}

public class PersistenceContext : IPersistenceContext, IDisposable
{
    private readonly FluentConfiguration _configuration;
    private readonly ISessionFactory _sessionFactory;

    public PersistenceContext(FluentConfiguration configuration)
    {
        _configuration = configuration;
        _sessionFactory = _configuration.BuildSessionFactory();
    }

    public FluentConfiguration Configuration { get { return _configuration; } }
    public ISessionFactory SessionFactory { get { return _sessionFactory; } }

    public ISession CurrentSession
    {
        get
        {
            if (!CurrentSessionContext.HasBind(SessionFactory))
            {
                OnContextualSessionIsNotFound();
            }
            var contextualSession = SessionFactory.GetCurrentSession();
            if (contextualSession == null)
            {
                OnContextualSessionIsNotFound();
            }
            return contextualSession;
        }
    }

    public void Dispose()
    {
        SessionFactory.Dispose();
    }

    private static void OnContextualSessionIsNotFound()
    {
        throw new InvalidOperationException("Ambient instance of contextual session is not found. Open the db session before.");
    }

}

public class DbSession : IDisposable
{
    private readonly ISessionFactory _sessionFactory;

    public DbSession(IPersistenceContext persistentContext)
    {
        _sessionFactory = persistentContext.SessionFactory;
        CurrentSessionContext.Bind(_sessionFactory.OpenSession());
    }

    public void Dispose()
    {
        var session = CurrentSessionContext.Unbind(_sessionFactory);
        if (session != null && session.IsOpen)
        {
            try
            {
                if (session.Transaction != null && session.Transaction.IsActive)
                {
                    session.Transaction.Rollback();
                }
            }
            finally
            {
                session.Dispose();
            }
        }
    }
}

这里有一个repository helper class。正如你所看到的,每个DB调用都有锁,所以并发DB调用不会出现,对于不同的线程也是如此,因为_locker对象是静态的。

public abstract class BaseEntityRepository<T, TId> : IBaseEntityRepository<T, TId> where T : BaseEntity<TId>
{
    private ITransaction _transaction;
    protected static readonly object _locker = new object();

    public bool Save(T item)
    {
        bool result = false;

        if ((item != null) && (item.IsTransient()))
        {
            lock (_locker)
            {
                try
                {
                    _transaction = session.BeginTransaction();
                    nHibernateHelper.CurrentSession.Save(item);
                    nHibernateHelper.Flush();
                    _transaction.Commit();          
                    result = true;
                } catch 
                {
                    _transaction.Rollback();
                    throw;
                }
                //DelayAfterProcess();
            }
        }
        return result;
    }

    //same for delete and update 

    public T Get(TId itemId)
    {
        T result = default(T);

        lock (_locker)
        {
            try
            {
                result = nHibernateHelper.CurrentSession.Get<T>(itemId);
            }
            catch 
            {
                throw;
            }
        }
        return result;
    }

    public IList<T> Find(Expression<Func<T, bool>> predicate)
    {
        IList<T> result = new List<T>();
        lock (_locker)
        {
            try
            {
                result = nHibernateHelper.CurrentSession.Query<T>().Where(predicate).ToList();
            }
            catch 
            {
                throw;
            }
        }
        return result;
    }

}

我像这样使用以前的类(我在每个线程调用一次nHibernateHelper.OpenConnection())。仓库由singletone示例化:

using (nHibernateHelper.OpenConnection())
{
    Foo foo = new Foo();
    FooRepository.Instance.Save(foo);
}

我尝试将IsolationLevel更改为ReadCommited,但这并没有改变问题。我还试图通过将SQLite日志模式从journal改为WAL来解决这个问题:

using (nHibernateHelper.OpenConnection()) 
{
    using (IDbCommand command = nHibernateHelper.CurrentSession.Connection.CreateCommand())
    {
        command.CommandText = "PRAGMA journal_mode=WAL";
        command.ExecuteNonQuery();
    }
}

这有助于计算机与快速硬盘驱动器,但在一些我得到了同样的错误.然后我尝试在仓库中添加“DB update file exist”检查,并在每次保存/更新/删除过程后延迟:

protected static int _delayAfterInSeconds = 1;
    protected void DelayAfterProcess()
    {
        bool dbUpdateInProcess = false;
        do
        {
            string fileMask = "*-wal*";
            string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), fileMask);
            if ((files != null) && (files.Length > 0))
            {
                dbUpdateInProcess = true;
                Thread.Sleep(1000);
            }
            else
            {
                dbUpdateInProcess = false;
            }
        } while (dbUpdateInProcess);
        if (_delayAfterInSeconds > 0)
        {
            Thread.Sleep(_delayAfterInSeconds * 1000);
        }
    }

相同的解决方案(检查数据库更新文件)不适用于日志文件。它报告说,该日志文件被删除,但我仍然得到错误。For -wal文件它的工作(正如我所认为的。我需要更多的时间来测试它)。但这种解决方案严重刹车程序。
也许你能帮我

shstlldc

shstlldc1#

为我自己祈祷。问题与.IsolationLevel(IsolationLevel.Serializable)相关。当我将此行更改为.IsolationLevel(IsolationLevel.ReadCommitted)时,问题消失了。

rt4zxlrg

rt4zxlrg2#

sqlite被设计成这样的“锁定”,因此在名称中的lite。它仅为一个客户端连接而设计。
但是你可以为应用程序的不同区域使用多个数据库文件,这可能会拖延问题,直到你的用户群再次增长。

wgeznvg7

wgeznvg73#

我个人使用这个技巧:
假设程序A输出SQL插入/更新或任何其他事务,程序B也做同样的事情。(或10-20个程序/线程)
我这样做:

mkfifo mydbfifo
nohup sqlite3 mydb.db <mydbfifo &
nohup programA >mydbfifo &
nohup programB >mydbfifo &

等等。

相关问题