NHibernate and database connection failover?

这一生的挚爱 提交于 2019-12-01 23:07:19

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)");
        }
    }
}
Richard Howes

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.

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