休眠和会话池 [英] Nhibernate and session pooling

查看:94
本文介绍了休眠和会话池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,应该每隔1秒钟将一个新的消息插入表中.在EntityFramework中,有一种称为连接池的连接,这使它成为使上下文的生存期尽可能短的更好选择.我们处理上下文.这是否适用于Nhibernate会话?

I'm working on a project where a new messeage should be insert into the table every 1 second. In EntityFramework, there is something called connection-pooling which makes it a better choice to keep the lifetime of the context as short as possible.We dispose the context. Does this apply to Nhibernate session?

ISessionFactory sf = cfg.BuildSessionFactory();
ISession session = sf.OpenSession();
While(true)
{
//.......
    using (var tran = session.BeginTransaction())
    {
        session.SaveOrUpdate(msg);
        tran.Commit();                           
    }
    Thread.Sleep(1000);
}

ISessionFactory sf = cfg.BuildSessionFactory();
While(true)
{
//.......
    using(var session = sf.OpenSession())
    {
     using (var tran = session.BeginTransaction())
     {
         session.SaveOrUpdate(msg);
         tran.Commit();                           
     }
     Thread.Sleep(1000);
    }
}

两者似乎都可以,但是我应该使用哪一个呢?

Both seem to work, but which one shall I use?

推荐答案

好吧,如果我决定仅回答您的问题:

第二个代码块更合适.实际上,连接池与NHibernate无关.这是基础RDBMS的行为.

second code block is more appropriate. Actually, connection pooling has nothing to do with NHibernate. It is behavior of underlying RDBMS.

在NHibernate中,创建SessionFactory的成本很高,并且在应用程序生命周期中只能执行一次(理想情况下是在启动时).创建ISession并不昂贵.建议您的会议尽可能短.

In NHibernate, creating SessionFactory is costly and should be done only once (at the startup ideally) in application lifetime. Creating ISession is not costly call. It is recommended that your session should be as short leaved as possible.

不仅仅是答案:

除了短暂的会话外,您还应考虑实施UnitOfWork(每次会话会话",即正确使用事务和会话),以提高一级缓存和批处理的优势.

Apart from short leaved session, you should also consider implementing UnitOfWork ("session-per-conversation" i.e. properly using transaction and session) to improve benefits of first level cache AND Batching.

一级缓存是每个会话的.如果在新会话上运行每个数据库调用,则实际上将无法获得缓存优势.

First level cache is per session. If you run each DB call on new session, you are effectively not getting caching advantage.

批处理也是如此.批处理是根据您处理事务的方式完成的.调用tran.Commit();以及其他一些属性(例如nhSession.FlushModenhSession.SetBatchSize)起着重要的作用.请参阅文章.
为了实现批处理,我建议您改进您的 first 代码块,而不是在循环的每100次迭代(或10或500个适合您的迭代)中将事务提交到using块中.

Same is true for Batching. Batching is done based on how you handle your transactions. Call to tran.Commit(); plays important role along with some other properties like nhSession.FlushMode, nhSession.SetBatchSize. Refer this article.
To implement batching, I recommend you improve your first code block and instead of commiting the transaction in using block, you do it per 100 (or 10 or 500 whatever suits you) iterations of your loop.

引用这个问题.

请参考@a在评论中所说的答案.

Refer this answer as said by @Fran in comments.

这篇关于休眠和会话池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆