2014-01-15 34 views
2

我們使用Hibernate連接到MySQL數據庫。數據庫關閉時需要獲取警報的方法。正在閱讀有關Hibernate中的監聽器,但不確定是否可以使用它們中的任何一個來檢測數據庫關閉事件。如何檢測(在Hibernate中)數據庫何時關閉?

任何指針/幫助將不勝感激。謝謝。

+2

如果您試圖做某件事(如獲取實體)並且失敗,您只會知道數據庫已關閉。例外將取決於你使用的連接池(如果有的話)。最好的辦法就是取下數據庫,看看你在應用程序中遇到了什麼異常,並嘗試使用這些異常。 – Taylor

+0

Catch org.hibernate.exception.JDBCConnectionException – Bart

+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()); 
} 
}