我正在使用JPA来处理JBOSS中的实体。一个实体将在各种事务中被多个线程更新。我在我的实体中添加了@Version属性,并且在更新实体之前我获得了OptimisticLock.I无法处理异常和如果事务失败则重试。
实体
@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时帮助我重试。
在哪里处理异常? /在哪里写重试逻辑?
答案 0 :(得分: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>