java 使用@Async 嵌套@Transactional 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29258436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested @Transactional methods with @Async
提问by Michael Ressler
I'm using Spring with JPA. I have @EnableAsync
and @EnableTransactionManagement
turned on. In my user registration service method, I have a few other service methods I call that are annotated @Async
. These methods do various things like sending a welcome email and registering the newly minted user with our third party payment system.
我正在将 Spring 与 JPA 一起使用。我有@EnableAsync
并@EnableTransactionManagement
打开。在我的用户注册服务方法中,我调用了其他一些带有注释的服务方法@Async
。这些方法可以执行各种操作,例如发送欢迎电子邮件和在我们的第三方支付系统中注册新创建的用户。
Everything works well until I want to verify that the third party payment system successfully created the user. At that point, the @Async
method attempts to create a UserAccount
(that references the newly minted User
) and errors out with a javax.persistence.EntityNotFoundException: Unable to find com.dk.st.model.User with id 2017
一切正常,直到我想验证第三方支付系统是否成功创建了用户。在这一点上,该@Async
方法尝试创建一个UserAccount
(引用新铸造的User
)并使用一个错误javax.persistence.EntityNotFoundException: Unable to find com.dk.st.model.User with id 2017
The register call looks like this:
注册调用看起来像这样:
private User registerUser(User newUser, Boolean waitForAccount) {
String username = newUser.getUsername();
String email = newUser.getEmail();
// ... Verify the user doesn't already exist
// I have tried all manner of flushing and committing right here, nothing works
newUser = userDAO.merge(newUser);
// Here is where we register the new user with the payment system.
// The User we just merged is not /actually/ in the DB
Future<Customer> newCustomer = paymentService.initializeForNewUser(newUser);
// Here is where I occasionally (in test methods) pause this thread to wait
// for the successful account creation.
if (waitForAccount) {
try {
newCustomer.get();
} catch (Exception e) {
logger.error("Exception while creating user account!", e);
}
}
// Do some other things that may or may not be @Aysnc
return newUser;
}
The payment service calls out to do its work of registering the user and looks like this:
支付服务调用完成其注册用户的工作,如下所示:
@Async
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Future<Customer> initializeForNewUser(User newUser) {
// ... Set up customerParams
Customer newCustomer = null;
try {
newCustomer = Customer.create(customerParams);
UserAccount newAccount = new UserAccount();
newAccount.setUser(newUser);
newAccount.setCustomerId(newCustomer.getId());
newAccount.setStatus(AccountStatus.PRE_TRIAL);
// When merging, JPA cannot find the newUser object in the DB and complains
userAccountDAO.merge(newAccount);
} catch (Exception e) {
logger.error("Error while creating UserAccount!", e);
throw e;
}
return new AsyncResult<Customer>(newCustomer);
}
The StackOverflow answer listed heresuggests that I set a REQUIRES_NEW
propagation, which I have done, but with no such luck.
这里列出的 StackOverflow 答案表明我设置了一个REQUIRES_NEW
传播,我已经完成了,但没有这样的运气。
Can anyone point me in the right direction? I really don't want to have to call the paymentService directly from my controller method. I feel that it should be a service level call for sure.
任何人都可以指出我正确的方向吗?我真的不想直接从我的控制器方法中调用 paymentService。我觉得这肯定应该是一个服务级别的电话。
Thanks for any help!
谢谢你的帮助!
采纳答案by Michael Ressler
With Vyncent's help, here is the solution that I arrived at. I created a new class called UserCreationService
and put all of the method that handled User
creation in that class. Here is an example:
在 Vyncent 的帮助下,这是我得出的解决方案。我创建了一个名为的新类UserCreationService
,并将所有处理User
创建的方法放在该类中。下面是一个例子:
@Override
public User registerUserWithProfileData(User newUser, String password, Boolean waitForAccount) {
newUser.setPassword(password);
newUser.encodePassword();
newUser.setJoinDate(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
User registered = userService.createUser(newUser);
registered = userService.processNewRegistration(registered, waitForAccount);
return userService.setProfileInformation(registered);
}
You'll notice that there is NO@Transactional
annotation on this method. This is on purpose. The corresponding createUser
and processNewRegistration
definitions look like this:
您会注意到此方法没有@Transactional
注释。这是故意的。对应的createUser
和processNewRegistration
定义如下所示:
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public User createUser(User newUser) {
String username = newUser.getUsername();
String email = newUser.getEmail();
if ((username != null) && (userDAO.getUserByUsername(username) != null)) {
throw new EntityAlreadyExistsException("User already registered: " + username);
}
if (userDAO.getUserByUsername(newUser.getEmail()) != null) {
throw new EntityAlreadyExistsException("User already registered: " + email);
}
return userDAO.merge(newUser);
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public User processNewRegistration(
User newUser,
Boolean waitForAccount)
{
Future<UserAccount> customer = paymentService.initializeForNewUser(newUser);
if (waitForAccount) {
try {
customer.get();
} catch (Exception e) {
logger.error("Error while creating Customer object!", e);
}
}
// Do some other maintenance type things...
return newUser;
}
Vyncent was spot on that transaction management was the issue. Creating the other service allowed me to have better control over when those transactions committed. While I was hesitant to take this approach initially, that's the tradeoff with Spring managed transactions and proxies.
Vyncent 认为事务管理是问题所在。创建其他服务使我能够更好地控制这些事务的提交时间。虽然我最初对采用这种方法犹豫不决,但这是与 Spring 管理的事务和代理的权衡。
I hope this helps someone else save some time later.
我希望这有助于其他人稍后节省一些时间。
回答by Vyncent
Make a try by creating a new UserServiceclass to manage user check, like so
尝试创建一个新的UserService类来管理用户检查,就像这样
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public User createOrUpdateUser(User newUser) {
String username = newUser.getUsername();
String email = newUser.getEmail();
// ... Verify the user doesn't already exist
// I have tried all manner of flushing and committing right here, nothing works
newUser = userDAO.merge(newUser);
return newUser;
}
then in the actual class, change
然后在实际课程中,更改
private User registerUser(User newUser, Boolean waitForAccount) {
String username = newUser.getUsername();
String email = newUser.getEmail();
// ... Verify the user doesn't already exist
// I have tried all manner of flushing and committing right here, nothing works
newUser = userDAO.merge(newUser);
by
经过
private User registerUser(User newUser, Boolean waitForAccount) {
newUser = userService.createOrUpdateUser(newUser);
The new userService with @Transactional REQUIRES_NEWshould force the commit and solve the issue.
带有@Transactional REQUIRES_NEW的新 userService应该强制提交并解决问题。