Spring @Retryable与有状态的Hibernate对象 [英] Spring @Retryable with stateful Hibernate Object

查看:59
本文介绍了Spring @Retryable与有状态的Hibernate对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使Springs @Retryable在失败时重试服务方法.

I am trying to make my Service Method retrying on failure with Springs @Retryable.

@Retryable(backoff = @Backoff(delay = 1000), maxAttempts = 3)
@Transactional(rollbackFor = Throwable.class)
public Something saveSomething(Something something) {
  //some logic and saving
}

问题是,保存对象对象后出现异常.因此,事务将回滚,并再次调用该方法.区别在于,something-object的id不再为null,而是它从Hibernate先前的保存过程中获得的值,因此,在第二次尝试中,Hibernate不会保存该对象,而是尝试对其进行更新.由于数据库中没有条目,因此更新不会执行任何操作,并且该对象也不会固定在数据库中.

The Problem is, that the exception appears after saving the something-object. So the Transaction is rolled back and the Method is called again. The Difference is that the id of the something-object is not null anymore but the value it got from the previous saving process by Hibernate so in the second attempt Hibernate does not save the object but tries to update it. Since no entry is in the DB the update doesn't do anything and the object is not persited to the DB.

认识到这一点后,我尝试将@Retryable的有状态属性设置为true:

After recognizing this i tried to set the stateful property of @Retryable to true:

@Retryable(backoff = @Backoff(delay = 1000), maxAttempts = 3, stateful = true)
@Transactional(rollbackFor = Throwable.class)
public Something saveSomething(Something something) {
  //some logic and saving
}

但是使用该配置,saveSomething()只会被调用一次,而der不会被第二次尝试.

But with that config saveSomething() is just called once and der is no second attempt.

有人建议解决这个问题吗?

Has anyone suggestions to solve this problem?

推荐答案

使用有状态重试时;调用方必须再次调用该方法以进行下一次重试;该州维持已经进行了多少次尝试.因此,您必须使用try/catch并在循环中调用 saveSomething (使用新的 Something 或将id设置为null),直到成功为止-使用 @Recover 方法用于尝试重试的时间,可以在其中引发不同的异常,以便调用方知道应该重试的内容与尝试重试的时间之间的区别.

When you use stateful retry; the caller has to call the method again for the next retry; the state maintains how many attempts have been made. So, you have to use try/catch and call saveSomething in a loop (with a new Something, or setting the id to null) until it succeeds - using an @Recover method for when retries are exhausted, where you can throw a different exception so the caller knows the difference between something that should be retried and when retries are exhausted.

这篇关于Spring @Retryable与有状态的Hibernate对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆