gpt4 book ai didi

java - hibernate 延迟写入

转载 作者:搜寻专家 更新时间:2023-11-01 02:52:25 24 4
gpt4 key购买 nike

我想知道 hibernate 是否有可能延迟它对数据库的写入。我为mysql配置了hibernate。我希望支持的场景是 80% 读取和 20% 写入。所以我不想优化我的写入,我宁愿让客户端等到数据库被写入,而不是更早返回。我的测试目前有 100 个客户端并行,CPU 有时会达到极限。我需要这个 flush 方法来立即写入 DB 并仅在写入数据时返回。

在我的客户端,我发送一个写入请求,然后发送一个读取请求,但读取请求有时会返回 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();
}

最佳答案

@Siddharth Hibernate 并没有真正延迟编写响应,而且您的代码也不相同。我之前也遇到过类似的问题,怀疑你是否也面临同样的问题,即当有大量写入 hibernate 的请求时,是否有许多线程共享你的数据库的相同实例,甚至 hibernate 连续提交你真的看不到任何变化.您也可以通过在事务期间简单地查看 MySQL 日志来发现这一点,看看究竟出了什么问题!

关于java - hibernate 延迟写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8846702/

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