NHibernate and database connection failover?

后端 未结 2 1210
栀梦
栀梦 2021-01-21 07:39

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

相关标签:
2条回答
  • 2021-01-21 08:06

    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.

    0 讨论(0)
  • 2021-01-21 08:10

    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)");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题