gpt4 book ai didi

java - 回滚时取消 ejb 定时器

转载 作者:行者123 更新时间:2023-11-29 03:15:24 24 4
gpt4 key购买 nike

有没有办法确保在发生异常时取消周期性(每 10 秒)和持久性计时器? @Timeout 方法的实现是这样的(从遗留代码中简化而来):

@Timeout
@TransactionAttribute(REQUIRES_NEW)
public void onTimeout(Timer timer) {
try {
doSomeBusinessLogic();
} catch (Exception e) {
// throwing this exception makes sure rollback is triggered
throw new EJBException(e);
}
}

doSomeBusinessLogic() 发生任何异常时,需要回滚其事务。这工作正常。但是,我还要确保取消计时器。

直接的解决方案是将 timer.cancel() 放在 catch block 中。然而,这是行不通的,因为取消也会被回滚(JEE6 Turorial):

An enterprise bean usually creates a timer within a transaction. If this transaction is rolled back, the timer creation also is rolled back. Similarly, if a bean cancels a timer within a transaction that gets rolled back, the timer cancellation is rolled back. In this case, the timer’s duration is reset as if the cancellation had never occurred.

如果发生异常/回滚,我如何确保取消计时器(防止任何进一步的超时)?设置最大重试次数也足够了,但我认为 JBoss 不支持这一点。

应用服务器是JBoss AS 7.2。

最佳答案

我也尝试了 Sergey 提出的解决方案,它似乎有效 - 计时器被取消。在 JBoss EAP 6.2 上测试。这是我用于测试的代码:

@Stateless
public class TimeoutTest implements TimeoutTestLocal {

@Resource
TimerService timerService;

@Resource
SessionContext sessionContext;

@Timeout
@TransactionAttribute(TransactionAttributeType.NEVER)
public void tmout(javax.ejb.Timer timer) {
try {
System.out.println("timout invoked");
//instead of internal call let's invoke doNothing as
//this timeout callback is client of TimeoutTest EJB
//in this way doNothing will be run inside transaction
TimeoutTestLocal local = sessionContext.getBusinessObject(TimeoutTestLocal.class);
local.doNothing();
} catch (Exception e) {
timer.cancel();
System.out.println("Timer cancelled");
}
}

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void doNothing() {
throw new EJBException("RE Exception");
}


@Override
public void schedule() {
timerService.createTimer(5000, 10000, "test");
}
}

关于java - 回滚时取消 ejb 定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26973933/

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