如何在数据库出现故障时检测(在Hibernate中)?

时间:2014-01-15 07:13:13

标签: java mysql hibernate

我们正在使用Hibernate连接到MySQL数据库。需要一种在数据库发生故障时获取警报的方法。正在阅读Hibernate中的监听器,但不确定是否可以使用其中任何一个来检测数据库关闭事件。

1 个答案:

答案 0 :(得分:0)

正如@Bart在上面的评论中所建议的,尝试通过以下代码实现功能。请随时提出任何改进或替代方案。

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.JDBCConnectionException;

public class PollingThread extends Thread {

private static final Logger LOGGER = Logger.getLogger(PollingThread.class);
private long interval;

public PollingThread() {
    // default polling interval set to 5 seconds
    this(TimeUnit.SECONDS.toMillis(5));
}

public PollingThread(final long interval) {
    this.interval = interval;
    this.setDaemon(true);
    LOGGER.debug("Polling thread initialized!");
}

@Override
public void run() {

    while (true) {
        boolean connected = poll();
        LOGGER.debug("Connected - " + connected);

        if (!connected) {
            // TODO connect to fail-over database
        }

        synchronized (this) {
            try {
                wait(interval);
            } catch (InterruptedException ex) {
                LOGGER.warn("Polling thread interrupted", ex);
            }
        }
    }
}

private boolean poll() {

    boolean connected = true;
    try {
        final Session session = HibernateUtil.getSessionFactory().openSession();
        final Transaction tx = session.beginTransaction();
        tx.commit();
        session.close();
    } catch (JDBCConnectionException ex) {
        connected = false;
    }

    return connected;
}

public static void main(String[] args) {

    Executors.newSingleThreadExecutor().execute(new PollingThread());
}
}