gpt4 book ai didi

java - PlayFramework:捕获死锁并重新发出交易

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:39 26 4
gpt4 key购买 nike

我正在运行 Play!应用程序并正在调试死锁。

我看到的错误消息是从 Play 记录的!是:
尝试获取锁时发现死锁;尝试重新启动事务
无法将数据库状态与 session 同步
org.hibernate.exception.LockAcquisitionException:无法执行 JDBC 批量更新

来自Play! Documentation

Play will automatically manage transactions for you. It will start a transaction for each HTTP request and commit it when the HTTP response is sent. If your code throws an exception, the transaction will automatically rollback.

来自MySQL Documentation

you must write your applications so that they are always prepared to re-issue a transaction if it gets rolled back because of a deadlock.

我的问题:
在我的游戏中如何以及在哪里!应用程序可以捕获这些回滚事务并处理它们(选择重新发出它们、忽略它们等...)吗?

已更新
虽然我最终接受了已接受答案中的建议,并寻找死锁的原因(你知道 MySQL 外键约束会增加死锁的机会吗?现在我知道了!),这里有一些代码对我有用捕获并重新发出失败的保存。

boolean success = false;
int tries = 0;
while (!success && tries++ < 3) {
try {
updated.save();
success = true;
} catch (javax.persistence.PersistenceException e) {
pause(250);
}
}

最佳答案

您可以使用自定义增强器并增强插件中的所有 Controller 。

例如,增强器添加 catch block 并重新启动请求调用。重启请求比 Controller 内部的部分逻辑更可靠:

package plugins;
..
final public class ReliableTxPlugin extends PlayPlugin {
public void enhance(final ApplicationClasses.ApplicationClass applicationClass) throws Exception {
new TxEnhancer().enhanceThisClass(applicationClass);
}
}



package enhancers;
..
class TxEnhancer extends Enhancer {

public static void process(PersistenceException e) throws PersistenceException {
final Throwable cause = e.getCause();
if (cause instanceof OptimisticLockException || cause instanceof StaleStateException) {
final EntityTransaction tx = JPA.em().getTransaction();
if (tx.isActive()) {
tx.setRollbackOnly();
}
Http.Request.current().isNew = false;
throw new Invoker.Suspend(250);
}
throw e;
}
public void enhanceThisClass(final ApplicationClass applicationClass) throws Exception {
// .. general encahcer code
ctMethod.addCatch("enhancers.TxEnhancer.process(_e);return;",
classPool.makeClass("javax.persistence.PersistenceException"), "_e");
//..
}
}

关于java - PlayFramework:捕获死锁并重新发出交易,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7322297/

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