使用@Async嵌套@Transactional方法 [英] Nested @Transactional methods with @Async

查看:2300
本文介绍了使用@Async嵌套@Transactional方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring和JPA。我已打开 @EnableAsync @EnableTransactionManagement 。在我的用户注册服务方法中,我还有一些其他我称之为 @Async 的服务方法。这些方法可以执行各种操作,例如发送欢迎电子邮件以及使用我们的第三方支付系统注册新创建的用户。

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.

在我想验证第三方之前,一切正常支付系统成功创建了用户。此时, @Async 方法尝试创建 UserAccount (引用新建的用户)和错误输出 javax.persistence.EntityNotFoundException:无法找到ID为2017的com.dk.st.model.User

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

注册调用如下所示:

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);
}

StackOverflow答案列出这里建议我设置 REQUIRES_NEW 传播,我已经完成了,但没有这样的运气。

The StackOverflow answer listed here suggests that I set a REQUIRES_NEW propagation, which I have done, but with no such luck.

有人能指出我正确的方向吗?我真的不想直接从我的控制器方法调用paymentService。我觉得这应该是一个服务级别的电话。

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.

感谢您的帮助!

推荐答案

在Vyncent的帮助下,这是我到达的解决方案。我创建了一个名为 UserCreationService 的新类,并在该类中放置了处理 User 创建的所有方法。下面是一个示例:

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:

@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);
}

您会注意到 @Transactional 此方法的注释。这是故意的。相应的 createUser processNewRegistration 定义如下所示:

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:

@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是该事务管理的问题。创建其他服务使我能够更好地控制何时提交这些事务。虽然我最初对采用这种方法犹豫不决,但这是对Spring托管交易和代理的权衡。

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.

我希望这可以帮助其他人节省一些时间。

I hope this helps someone else save some time later.

这篇关于使用@Async嵌套@Transactional方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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