我想知道是否有可能将hibernate延迟写入数据库。我已经为mysql配置了hibernate。我希望支持的方案是80%
次读取和20%
次写入。所以我不想优化我的写入,我宁愿让客户端等到DB被写入,而不是提前返回。我的测试目前有100个并行客户端,cpu有时会最大化。我需要这个flush方法立即写入DB并且仅在写入数据时返回。
在我的客户端,我发送写请求然后发送读请求,但读请求有时会返回null。我怀疑hibernate没有立即写入db。
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();
}
答案 0 :(得分:2)
@Siddharth Hibernate并没有真正延迟编写响应,而且你的代码也没有说同样的话。我之前也遇到过类似的问题,并怀疑你可能面临同样的问题,那就是当有大量写入hibernate的请求时,很多线程共享你的数据库的同一个实例,甚至有hibernate的连续提交,你真的没有看到任何变化。 您也可以通过在事务期间简单地查看MySQL日志来了解这一点,看看到底出了什么问题!
答案 1 :(得分:2)
感谢您的提示。花了我一些时间来调试。 Mysql日志很棒。
这是我运行以检查插入和mysql写入的时间戳。 mysql在binlog中记录所有数据库操作。要阅读它,我们需要使用名为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之前,服务器调用不会返回。