gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:17:53 25 4
gpt4 key购买 nike

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

最佳答案

正如@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());
}
}

关于java - 如何检测(在 Hibernate 中)数据库何时出现故障?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21131185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com