如何使用数据库作为备份/故障切换在hibernate? [英] How to use database as backup/failover in hibernate?
问题描述
我的应用程序是基于hibernate从mysql服务器获取数据。这个mysql服务器被复制到另一个mysql服务器实例。今天,我有一个停机时间,因为主数据库服务器没有任何通知。为了避免任何未来的意外问题,我计划添加一个功能,如果发现主要数据库,系统将连接到辅助数据库。
My application is based on the hibernate to fetched data from a mysql server. This mysql server is replicated to another mysql server instance. Today, I got a downtime as the primary database server was gone down without any notice. To avoid any future accidental problem, I am planing to add a functionality that will enable system to connect to secondary database if it finds the primary down.
是否存在一种方法
推荐答案
我在创建一个想法表单后创建了下面的类这个线程
它似乎运行良好。我不知道这是否是一个好的方法。
I have created following class after getting an idea form this thread It seems to be working well. I don't know if this is a good approach at all.
package com.vsd.server.hibernate;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.connection.C3P0ConnectionProvider;
public class FailoverConnectionProvider extends C3P0ConnectionProvider {
String password;
String username;
String connectionString;
String failover_connstring;
@Override
public Connection getConnection() throws SQLException {
Connection conn = null;
try {
conn = DriverManager.getConnection(connectionString, username, password);
} catch (Exception ex) {
conn = DriverManager.getConnection(failover_connstring, username, password);
}
if(conn == null){
throw new IllegalStateException("Database connection was not initialized");
}
return conn;
}
@Override
public void configure(Properties properties) throws HibernateException {
failover_connstring = properties.getProperty("hibernate.connection.failover.url");
if (StringUtils.isBlank(connectionString)
&& StringUtils.isBlank(failover_connstring)
&& StringUtils.isBlank(username)
&& StringUtils.isBlank(password)) {
throw new IllegalStateException("Unable to initialize connection provider for hibernate");
}
}
}
这篇关于如何使用数据库作为备份/故障切换在hibernate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!