【问题标题】:NHibernate: how to set connection timeoutNHibernate:如何设置连接超时
【发布时间】:2015-07-06 09:05:14
【问题描述】:

在 NHibernate 中的连接失败(连接超时)之前,有什么方法可以全局设置您将等待连接到给定数据库的时间?在 ADO.NET 中,您可以像这样为单个连接执行此操作:

new SqlConnection().ConnectionTimeout = 10;

我找到了如何设置在命令执行失败here(命令超时)之前等待结果集的时间。但是,显然,这不是我需要的

【问题讨论】:

    标签: c# nhibernate connection-timeout


    【解决方案1】:

    您可以在您的 NHibernate 配置代码中使用 connection_timeout 设置。详情请参阅3.4 of the documentation 部分。

    为此的XML配置如下...

    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
        <session-factory>
            <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
            <property name="connection.connection_string">
                Server=(local);initial catalog=theDb;Integrated Security=SSPI
            </property>
            <property name="connection_timeout">100</property>
        </session-factory>
    </hibernate-configuration>
    
    <!-- other app specific config follows -->
    

    我使用的是 Fluent NHibernate,所以我的配置代码如下...

    FluentConfiguration configuration = Fluently.Configure()
                             .Database(MsSqlConfiguration.MsSql2012.ConnectionString(ConnectionString))
                             .ExposeConfiguration(cfg => cfg
                                .SetProperty("connection_timeout", "100")
                             .Mappings(m =>
                             {
                                 var cfg = CreateAutomappings();
                                 m.AutoMappings.Add(cfg);
                             });
    

    【讨论】:

    • 命令超时连接超时是有区别的。请参考here。您提供的代码设置了命令超时,但我需要一种方法来设置连接超时
    • 连接超时 != 命令超时,即连接超时是等待连接可用的时间,但命令超时是最大命令执行时间
    • 正如其他人所说,我们正在寻找连接超时,而不是命令超时。您的回答具有误导性,可能会导致某人更改错误的设置,这就是我投反对票的原因。
    • 是的,在回答时我最初输入的是命令而不是连接——我猜这是一个容易犯的错误。没有打扰编辑,因为我觉得有人有足够的经验使用 NHibernate 会找出 connection_timeout 设置与其命令等效项一起存在。然而,有些人似乎特别烦恼——即使是在 5 年后——所以,为了他们的利益,我终于更新了它。
    • 没有connection_timeout这样的设置。
    【解决方案2】:

    您可以在连接字符串“Connection Timeout=x”上设置它。

    【讨论】:

    • 在我的情况下,这是解决问题的最简单方法。在某些其他情况下,编写custom connection provider 并以编程方式设置 IDbConnection.ConnectionTimeout 属性可能会更好
    • 请注意这里的“x”是以秒为单位的时间。
    【解决方案3】:

    使用 NHibernate,您可以自己提供连接:

    sessionFactory.openSession(myConnection);
    

    我不会推荐它,因为当会话由 NHibernate 管理时会更容易。

    您仍然可以编写自己的连接提供程序,它可以在创建的连接上设置您想要的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 2012-05-01
      • 2016-06-09
      相关资源
      最近更新 更多