【问题标题】:Does Hibernate automatically restart transactions upon deadlocking?Hibernate 会在死锁时自动重启事务吗?
【发布时间】:2014-12-12 23:42:26
【问题描述】:

关于这个话题已经有很多文章了:

我发现最后一个接受的答案特别有趣:

如果您使用 InnoDB 或任何行级事务 RDBMS,那么它 任何写事务都可能导致死锁,即使在 完全正常的情况。更大的表、更大的写入和长 事务块通常会增加死锁的可能性 发生。在你的情况下,它可能是这些的组合。

这意味着我们永远无法阻止它们,而只能处理它们。真的吗?我想知道如果有 1000 人在线调用写入数据库操作,您是否可以防止网站出现死锁。

谷歌搜索该主题并没有得到任何有趣的结果。我发现只有一个是这个(http://www.coderanch.com/t/415119/ORM/databases/Deadlock-problems-Hibernate-Spring-MS):

public class RestartTransactionAdviser implements MethodInterceptor {
    private static Logger log = Logger.getLogger(RestartTransactionAdviser.class);

    public Object invoke(MethodInvocation invocation) throws Throwable {
        return restart(invocation, 1);
    }

    private Object restart(MethodInvocation invocation, int attempt) throws Throwable {
        Object rval = null;
        try {
            rval = invocation.proceed();
        } catch (Exception e) {
            Throwable thr = ExceptionUtils.getRootCause(e);
            if (thr == null) {
                throw e;
            }

            if (StringUtils.contains(thr.getMessage(), "deadlock") || StringUtils.contains(thr.getMessage(), "try restarting transaction") || StringUtils.contains(thr.getMessage(),
                    "failed to resume the transaction")) {
                if (attempt > 300) {
                    throw e;
                }
                int timeout = RandomUtils.nextInt(2000);
                log.warn("Transaction rolled back. Restarting transaction.");
                log.debug("Spleep for " + timeout);
                log.debug("Restarting transaction: invocation=[" + invocation + "], attempt=[" + attempt + "]");
                Thread.sleep(timeout);
                attempt++;
                return restart(invocation, attempt);
            } else {
                throw e;
            }
        }
        return rval;
    }
}

另一方面,我严重怀疑这种解决方案的质量。您能否详细说明并解释死锁的最佳处理方式是什么?如何处理银行和企业应用程序中的死锁?

【问题讨论】:

  • 您对这样的解决方案有什么疑问?它是 AOP 捕获异常并在某些情况下重试。虽然 300 次重试可能有点陡峭。 Spring 也有一个小项目,Spring Retry(也被 Spring Integration 和 Spring Batch 用于这种逻辑)。
  • 这真的是尝试重启交易的最佳方式吗?难道真的没有办法在重负载数据库中防止它们吗?
  • 重试有什么问题。您可以尝试通过隔离数据库来阻止它们,但这样您的应用程序就会爬网......

标签: java mysql spring hibernate transactions


【解决方案1】:

休眠会话需要transaction write-behind 一级缓存。这使您可以将更改推迟到最后一个负责任的时刻,从而减少锁定获取间隔(即使在 READ_COMMITTED isolation level 中也会发生)。

这意味着您必须尽量减少所有交易时间,我建议您使用FlexyPool 进行此类努力。您需要确保所有事务尽可能短,以减少锁定间隔以提高可扩展性。

锁定引入了串行操作,根据Amdahl's law,可伸缩性与串行操作的总比例成反比。

我的建议是首先致力于减少交易间隔。索引将减少查询时间。 ORM 可能会产生糟糕的查询,因此请确保您的 integration tests verify expected queries against actual executed ones

p6spy 之类的工具可以非常方便地为您的查询计时,因此请确保您也使用它。

当所有事务都尽可能短而您仍需要更多并发性时,您可以转向水平可扩展性。您可以先从同步主从复制策略开始,将读取重定向到节点从属,同时保留主节点进行写入事务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 2014-12-22
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 2013-07-18
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多