SpringBoot the try / catch exception and roll back the transaction (rollback automatic / manual rollback / partial rollback)

Business needs

Implement an asynchronous task, task status is recorded first execution , the direct return the results to the front end, and then the business logic to perform tasks asynchronously, if an exception is thrown during the execution, the capture of the abnormal state and update task fails ; if not thrown , update task status is executed successfully

Exception Handling

1, automatic rollback

    @Transactional(rollbackFor = Exception.class)
    public void asyncJob() throws Exception {
        success();
        //假如exception这个操作数据库的方法会抛出异常,方法success()对数据库的操作会回滚
        exception();
    }

2, rolled back manually (for try / catch, and throw rollback)

    @Transactional(rollbackFor = Exception.class)
    public void asyncJob() {
        success();
        try {
            exception();
        } catch (Exception e) {
            e.printStackTrace();
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

3, the abnormal portion rollback

    @Transactional(rollbackFor = Exception.class)
    public void asyncJob() {
        success();
        //设置回滚点,只回滚以下异常
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            exception();
        } catch (Exception e) {
            e.printStackTrace();
            //手工回滚异常,回滚到savePoint
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
        }
    }

Fake code

    @Autowired
    private AsyncJobService asyncJobService;

    @Transactional(rollbackFor = Exception.class)
    public Boolean executeJob() {
        checkProcessJob();//检查是否存在流程中的任务
        Job job = new Job();
        job.setStatus(StatusEnum.IN_PROGRESS);//设置任务状态为执行中
        jobMapper.insert(job);

        asyncJobService.asyncExecute(job);//异步执行任务
        return true;
    }
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void asyncExecute(Job job) {
        //设置回滚点,只回滚以下异常
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            exception();
        } catch (Exception e) {
            //手工回滚异常,回滚到savePoint
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            log.error("异步执行任务失败,{}", e.getMessage());
            job.setStatus(StatusEnum.FAIL);//设置任务状态为执行失败
            jobMapper.updateById(job);
            return;
        }
        job.setStatus(StatusEnum.SUCCESS);//设置任务状态为执行成功
        jobMapper.updateById(job);
    }
Published 177 original articles · won praise 407 · views 80000 +

Guess you like

Origin blog.csdn.net/qq_40378034/article/details/104012100