休眠延迟写入

Sid*_*rth 5 java hibernate

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

在我的客户端,我发送一个写入请求,然后发送一个读取请求,但读取请求有时会返回 null。我怀疑休眠没有立即写入数据库。

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();
}
Run Code Online (Sandbox Code Playgroud)

San*_*alp 2

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