2012-01-13 93 views
3

我想知道是否有休眠延遲其寫入數據庫的可能性。我有配置爲MySQL的休眠。我希望支持的情景是80%的讀取和20%的寫入。所以我不想優化我的寫入,我寧願讓客戶端等到數據庫被寫入,而不是稍後返回。我的測試目前有100個並行的客戶端,cpu有時會最大限度地運行。我需要這種刷新方法立即寫入數據庫,並僅在數據寫入時才返回。休眠延遲寫

在我的客戶端,我發送了一個寫請求,然後發送了一個讀請求,但是這個讀請求有時會返回null。我懷疑hibernate沒有立即寫入數據庫。

public final ThreadLocal session = new ThreadLocal(); 

public Session currentSession() { 
    Session s = (Session) session.get(); 
    // Open a new Session, if this thread has none yet 
    if (s == null || !s.isOpen()) { 
     s = sessionFactory.openSession(); 
     // Store it in the ThreadLocal variable 
     session.set(s); 
    } 
    return s; 
} 
public synchronized void flush(Object dataStore) throws DidNotSaveRequestSomeRandomError { 
    Transaction txD; 
    Session session; 
    session = currentSession(); 
    txD = session.beginTransaction(); 
    session.save(dataStore); 
    try { 
     txD.commit(); 
    } catch (ConstraintViolationException e) { 
     e.printStackTrace(); 
     throw new DidNotSaveRequestSomeRandomError(dataStore, feedbackManager); 
    } catch (TransactionException e) { 
     log.debug("txD state isActive" + txD.isActive() + " txD is participating" + txD.isParticipating()); 
     log.debug(e); 
    } finally { 
     // session.flush(); 
     txD = null; 
     session.close(); 
    } 
    // mySession.clear(); 
} 

回答

2

@Siddharth Hibernate並沒有真正延遲寫入響應,而且你的代碼也不完全相同。我之前也遇到過類似的問題,懷疑你可能會面對同樣的情況,那就是,當有大量寫入hibernate的請求時,有很多線程共享你的數據庫的相同實例,甚至通過休眠連續提交,你真的沒有看到任何改變。 您也可以通過在交易期間簡單地查看MySQL日誌來了解這一點,並查看究竟發生了什麼問題!

+0

花了我一些時間進行調試。 Mysql日誌非常棒。所以這些是我調試的結果。如果我 – Siddharth 2012-01-16 05:14:44

2

感謝您的提示。花了我一些時間來調試。 Mysql日誌非常棒。 這是我運行檢查插入和mysql寫入時間戳。 mysql將所有數據庫操作記錄在二進制日誌中。要閱讀它,我們需要使用名爲mysqlbinlog的工具。 my.cnf也需要成爲「http://publib.boulder.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fgtpm7%2Fm7enablelogs.html 「

我檢查哪一個是最新的mysql bin日誌文件,並運行這個grep在日誌上方的1行以獲取時間戳。然後在java中,我調用Calendar.getInstance()。getTimeInMilli()來與時間戳進行比較。 sudo mysqlbinlog mysql/mysql-bin.000004 | grep「mystring」-1

所以我調試了我的問題。這是一個延遲寫入問題。所以我實現了同步寫入,而不是所有的異步。換句話說,服務器調用不會返回,直到db被刷新爲這個對象。

+1

我進一步調試,發現我的mysql bin日誌正在寫入數據庫「SET TIMESTAMP = 1327039370/*!* /插入到」。我的閱讀發生在「1327039372711」(java new Calendar.getInstance()。getTimeInMilli())。似乎我的寫作是在我閱讀之前發生的,但是閱讀失敗。我正在使用hibernate「Query rowResult = session.createSQLQuery(rowQuery).addEntity(table.getClass());」 – Siddharth 2012-01-20 06:12:50

+0

我面臨同樣的問題,請你讓我知道如何改變異步調用來在休眠中同步 – 2015-03-12 10:33:11