【问题标题】:How to detect (in Hibernate) when the database goes down?当数据库出现故障时如何检测(在 Hibernate 中)?
【发布时间】:2014-01-15 07:13:12
【问题描述】:

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

【问题讨论】:

  • 只有当你尝试做某事(比如获取实体)并且失败时,你才会知道数据库已关闭。例外情况将取决于您正在使用的连接池(如果有的话)。 imo,最好的办法是关闭数据库并查看您在应用程序中遇到的异常并尝试处理这些异常。
  • 捕获 org.hibernate.exception.JDBCConnectionException
  • 捕捉异常当然是其中一种选择,但我想要一种更简洁的方式。我的意思是,当数据库出现故障时会收到警报。
  • 异常本身不算警报吗?如果不是,我不知道是什么。
  • 只有在有一些数据库活动的情况下才会发生异常。

标签: java mysql hibernate


【解决方案1】:

正如上面 cmets 中的@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());
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-25
    • 2013-10-08
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2012-12-05
    • 1970-01-01
    相关资源
    最近更新 更多