NHibernate and database connection failover?

天涯浪子 提交于 2019-12-31 02:19:15

问题


I am using NHibernate to connect to a legacy rdbms system. Under high production load the rdbms service fails. To maintain the availability we have a failover rdbms service. Is there a way to configure NHibernate to use the FailOver Connection String when the primary connection is down?

Additional Info: I am using Castle over NHibernate. If Castle provides handling of failover connections then that will also do it for me.


回答1:


You can build your own NHibernate.Connection.IConnectionProvider which provides failover support.

This should be a subclass of ConnectionProvider which overrides CloseConnection() GetConnection() and Configure().

The connection provider is specified in your hibernate configuration as property connection.provider.

Here is an untested implementation which is based on DriverConnectionProvider.

public class FailoverConnectionProvider : ConnectionProvider
{
    static string FailoverConnectionStringProperty = "connection.failover_connection_string";
    string failover_connstring;

    public override void CloseConnection(IDbConnection conn)
    {
        base.CloseConnection(conn);
        conn.Dispose();
    }

    public override IDbConnection GetConnection()
    {
        try {
            return GetConnection( ConnectionString );
        } catch {
            return GetConnection( failover_connstring );
        }
    }

    IDbConnection GetConnection( string connstring )
    {
        log.Debug("Obtaining IDbConnection from Driver");
        IDbConnection conn = Driver.CreateConnection();
        try {
            conn.ConnectionString = connstring;
            conn.Open();
        } catch (Exception) {
            conn.Dispose();
            throw;
        }

        return conn;
    }

    public override void Configure(IDictionary<string, string> settings)
    {
        base.Configure( settings );

        settings.TryGetValue(FailoverConnectionStringProperty, out failover_connstring);

        if (failover_connstring == null) {
            throw new HibernateException("Could not find connection string setting (set " + FailoverConnectionStringProperty + " property)");
        }
    }
}



回答2:


Nhiberbate uses ADO, which supplies a Failover Partner, for mirrored DBs and connection/server failures. There's a stackOverflow question HERE that relates to failover partner.



来源:https://stackoverflow.com/questions/2416813/nhibernate-and-database-connection-failover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!