0

我正在使用 JPA 处理 JBOSS 中的实体。一个实体将由多个线程在各种事务中更新。我在我的实体中添加了@Version 属性,并且在更新实体之前我正在获取 OptimisticLock。我无法处理异常并重试事务失败。

实体是

@Entity  
public class DataEntity   
{  
    @Id  
    int id;  
    long count;  
    @Version  
    int versionAttribute;  
     ....  
     ....  

更新实体的代码是

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateEntity()  
{  
     DataEntity d=entityManager.find(DataEntity.class,0,LockModeType.OPTIMISTIC);
     d.setCount(d.getCount()+1);  
}  

如您所见,方法 updateEntity() 使用 TransactionAttributeType.REQUIRES_NEW 来进行新事务。这里的事务是容器管理的。所以在抛出 OptimisticLockingException 时帮助我重试。

在哪里处理异常?/在哪里写重试逻辑?

4

1 回答 1

1

如何处理超出事务边界?

public class SafeHandleInterceptor implements MethodInterceptor {

private final Logger logger = LoggerFactory.getLogger();
private int maxRetryCount = 3;

public void setMaxRetryCount(int maxRetryCount) {
    this.maxRetryCount = maxRetryCount;
}

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    int retryCount = 0;
    while (true) {
        try {
            ReflectiveMethodInvocation inv = (ReflectiveMethodInvocation) invocation;
            // clone before proceed, each inv could be proceed only once
            MethodInvocation anotherInvocation = inv.invocableClone();
            return anotherInvocation.proceed();
        } catch (OptimisticException e) {
            if (retryCount++ >= maxRetryCount) {
                throw e;
            } else {
                logger.info("retry for exception:" + e.getMessage(), e);
                continue;
            }
        }
    }
}

}

编织:

<bean id="your original transactional bean name" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target" ref="reference to your original transactional bean" />
    <property name="proxyInterfaces"
        value="your interface" />
    <property name="interceptorNames" value="safeHandleInterceptor" />
</bean>
于 2013-07-30T09:25:34.377 回答