Spring @Transactional和@Async

时间:2019-06-28 08:29:17

标签: java spring spring-boot

在我的应用程序中,创建任务时,我需要向Google进行API调用以创建Google日历事件。

我决定在一个单独的线程上进行该API调用,这样我们的客户端就不必再等待更长的时间了。

@Override
@Transactional( rollbackFor = DataException.class )
public TaskResponseBean createTask( TaskCreationBean taskCreationBean, UserAccessDetails accessDetails )
        throws DataException
{
    String googleEventId = "";
    try
    {
        TaskServiceUtil.validateInputBeforeCreatingTask(taskCreationBean, accessDetails);

        MatterModel matterModel = matterService.giveMatterIfExistElseThrowException(taskCreationBean.getMatterId(),
                owner);

        //A task is unique for a user for a matter
        taskCommons.throwExceptionIfTaskNameAlreadyExistForTheMatter(taskCreationBean.getTaskName().trim(), owner,
                matterModel);

        TaskModel savedTask = taskModelRepository.save(savableTask);

        if( !NullEmptyUtils.isNull(savableTask.getDueDate()) )
        {
            final CreateEventBean createEventBean = getCreateEventBean(getEventParticipants(savedTask), savedTask);
            calendarTrigerer.triggerEventCreation(createEventBean, savedTask.getId(), null,
                    GoogleCalendarTrigerer.EVENT_TYPE_CREATE);
        }
        // Keep track of the list of assignees of a task
        if( taskCreationBean.getHaveAssignee() || taskCreationBean.getIsSelfAssigned() )
        {
            saveTaskAssignedHistory(savedTask, owner, savedTask.getAssignedTo(), false);
        }

    }
    catch( DataException e )
    {
        LOGGER.error(GeneralConstants.ERROR, e);
        if( !NullEmptyUtils.isNullOrEmpty(googleEventId) )
        {
            LOGGER.info("Deleting google event id {}", googleEventId);
            googleCalendarService.deleteGoogleCalendarEvent(googleEventId);
        }
        throw e;
    }
    catch( Exception e )
    {
        LOGGER.error(GeneralConstants.ERROR, e);
        if( !NullEmptyUtils.isNullOrEmpty(googleEventId) )
        {
            LOGGER.info("Deleting google event id {}", googleEventId);
            googleCalendarService.deleteGoogleCalendarEvent(googleEventId);
        }
        throw new DataException(GeneralConstants.EXCEPTION, GeneralConstants.SOMETHING_WENT_WRONG,
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

@Async
void triggerEventCreation( CreateEventBean createEventBean, Long taskId, String eventId, String eventType )
        throws DataException
{
    try
    {

        TaskModel taskModel = null;

        if( !NullEmptyUtils.isNullOrEmpty(taskId) )
        {
            int retryCount = 0;
            Optional<TaskModel> taskModelOptional = taskModelRepository.findByIdAndIsActiveTrue(taskId);
            while( !taskModelOptional.isPresent() )
            {
                System.out.println("NOT PRESENT***********************************************");
                taskModelOptional = taskModelRepository.findByIdAndIsActiveTrue(taskId);
                if( retryCount++ > 50 )
                {
                    throw new DataException(GeneralConstants.EXCEPTION, "Transaction is unable to commit",
                            HttpStatus.INTERNAL_SERVER_ERROR);
                }
            }

            taskModel = taskModelOptional.get();
        }

        switch ( eventType )
        {
            case EVENT_TYPE_CREATE :

                eventId = googleCalendarService.addGoogleCalendarEvent(createEventBean);
                System.out.println("ADDED EVENT***********************************************" + eventId);

                System.out.println("PRESENT***********************************************");
                taskModel.setGoogleEventId(eventId);
                taskModelRepository.save(taskModel);
                break;
            case EVENT_TYPE_DELETE :
                NullEmptyUtils.throwExceptionIfInputIsNullOrEmpty(eventId);
                googleCalendarService.deleteGoogleCalendarEvent(eventId);
                taskModel.setGoogleEventId(null);
                taskModel.setIsActive(false);
                taskModelRepository.save(taskModel);
                break;
            case EVENT_TYPE_UPDATE :
                NullEmptyUtils.throwExceptionIfInputIsNullOrEmpty(eventId);
                NullEmptyUtils.throwExceptionIfInputIsNullOrEmpty(createEventBean);

                taskModel.setGoogleEventId(
                        googleCalendarService.updateGoogleCalendarEvent(eventId, createEventBean));
                taskModelRepository.save(taskModel);
                break;
            default :
                throw new DataException(GeneralConstants.EXCEPTION, "Invalid eventType", HttpStatus.BAD_REQUEST);
        }

    }
    catch( DataException e )
    {
        log.error(GeneralConstants.ERROR, e);
        throw e;
    }
    catch( Exception e )
    {
        log.error(GeneralConstants.ERROR, e);
        throw new DataException(GeneralConstants.EXCEPTION,
                "Something went wrong while trigering create event action", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

在创建活动时我如何解决(确保它能正常工作) 在单独的线程中,我将迭代并等待直到创建任务,然后使用事件ID更新它并保存它。

但是,出现了一个新问题,当更新任务时,我已经在数据库中找到了它的详细信息。在更新方法中,我将更新后的值设置为TaskModel并执行taskModelRepo.save(),在另一个线程中,我正在调用google calendar更新API,并且在成功调用API之后,我必须更新相应的{{1 }}并保存。

这里的问题是,有时当我在Google API调用成功后按ID提取任务时,由于先前的事务尚未提交,我将获得具有未更新值的TaskModel

那么如何确保新线程仅在提交调用该方法的事务之后才运行?

1 个答案:

答案 0 :(得分:0)

您可以使用 Google Guava Event 总线解决此问题。这是一个发布-订阅模型,其中生产者负责发出事件,然后将这些事件传递到事件总线,并发送给订阅该事件的所有侦听器。

侦听器订阅一个事件,并在从生产者发布该事件时触发该事件,您可以让侦听器方法同步异步运行,具体取决于您使用的那种事件总线。

这里是链接:https://github.com/google/guava/wiki/EventBusExplained