多线程事务回滚

在开发中遇到多线程环境下@Transactional注解无法实现事务回滚的问题,原因是每个线程使用独立的数据库连接。解决方法是通过手动管理线程的事务状态,将事务状态放入同步集合,在异常发生时循环回滚。测试环境中正常,但在生产环境出现数据无法插入,可能是事务未提交,需手动提交。
摘要由CSDN通过智能技术生成
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(

最近开发,有地方需要用到多线程,每个线程里面处理多个方法,过程中遇到了一个问题,我们使用平时的@Transactional注解,就是当前一个方法执行完成(比如插入操作),后一个方法是不会事务回滚的。当时觉得很不可思议,后来经过半天时间,终于挖出原因,并成功解决。
我这里先说明原因:多线程底层连接数据库的时候,时使用的线程变量(TheadLocal),所以,开多少线程理论上就会建立多少个连接,每个线程有自己的连接,事务肯定不是同一个了。
解决办法:我强制手动把每个线程的事务状态放到一个同步集合里面。然后如果有单个异常,循环回滚每个线程。
代码如下:

1、注入

     @Autowired
     private PlatformTransactionManager transactionManager;

2、多线程操作

@Override
    public String importBatch(String url,String taskId) {
        if (StringUtils.isEmpty(taskId)){
            return "请选择外呼任务";
        }

        Task task = taskService.selectById(taskId);
        if (task == null){
            return "外呼任务不存在,Id为:"+taskId;
        }

        String filePath = tmpFilePath + url;
        List<Customer> customers = ExcelTemplateExportUtil.importExcel(filePath, 0, 1, Customer.class);
        if (CollectionUtils.isEmpty(customers)){
            return "Excel数据不能为空";
        }

        int totalCustomerCnt = customers.size();
        if (totalCustomerCnt > 5000){
            return "最多支持5000条,请分批导入";
        }

        //过滤掉空属性
        List<String> phones = new ArrayList<>();
        List<Customer> customersNotNull = new ArrayList<>();
        String corpCode = ExecutionContext.getCorpCode();
        String userId = ExecutionContext.getUserId();
        for (Customer customer : customers) {
            String phone = customer.getPhone();
            if (StringUtils.isEmpty(customer.getName()) || StringUtils.isEmpty(phone)){
                continue;
            }

            customersNotNull.add(customer);
            phones.add(phone);
        }

        String result = "";
        int notNullSize = customersNotNull.size();
        int size = customers.size();
        if (notNullSize < size){
            result += "存在客户名称或手机号码为空:"+(size - notNullSize)+"条记录";
        }

        //过滤手机号重复的
        List<Customer> validCustomers = new ArrayList<>();
        List<Customer> repeatCustomers = this.selectList(new EntityWrapper<Customer>().eq("corp_code", corpCode).in("phone", phones));
        if (CollectionUtils.isNotEmpty(repeatCustomers)){
            result += "<br/>存在手机号码重复:"+(repeatCustomers.size())+"条记录";
            List<String> repeatPhones = new ArrayList<>(repeatCustomers.size());
            for (Customer repeatCustomer : repeatCustomers) {
                repeatPhones.add(repeatCustomer.getPhone());
            }

            for (Customer customer : customersNotNull) {
                if (repeatPhones.contains(customer.getPhone())){
                    continue;
                }

                validCustomers.add(customer);
            }
        }else {
            validCustomers = customersNotNull;
        }

        for (Customer validCustomer : validCustomers) {
            validCustomer.setCustomerType(UkConstant.CUSTOMER_TYPE_INDIVIDUALITY);
            validCustomer.setChannelType(UkConstant.CHANNEL_TYPE_CALL_OUT);
            validCustomer.setCalloutTaskStatus(0);
            validCustomer.setCalloutDistributeStatus(0);
            validCustomer.setCalloutTaskId(taskId);
            validCustomer.setCorpCode(corpCode);
            validCustomer.setCreater(userId);
        }

        if (CollectionUtils.isEmpty(validCustomers)){
            return "成功导入:"+ 0 +"条记录<br/>"+result;
        }


        List<List<Customer>> customersList = new ArrayList<>();
        int total = validCustomers.size();
        int threads = 5;
        int oneSize = total/5 +1;
        int start = 0;
        int end = 0;

        for (int i = 0; i <threads ; i++) {
            start = i * oneSize;
            end = (i+1)*oneSize;
            if (i<threads-1){
                customersList.add(validCustomers.subList(start,end));
            }else {
                customersList.add(validCustomers.subList(start,validCustomers.size()));
            }
        }

        //先在开启多线程外面,定义一个同步集合:
        List<TransactionStatus> transactionStatuses = Collections.synchronizedList(new ArrayList<TransactionStatus>());
        CountDownLatch latch= new CountDownLatch(threads);

        for (int i = 0; i < threads; i++) {
            int finalI = i;
            ThreadPoolUtils.fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务,这样会比较安全些。
                    TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
                    transactionStatuses.add(status);
                    try{
//执行业务逻辑  插入或更新操作
                        improtInsertBath(corpCode,userId,customersList.get(finalI));
                    }catch(Exception e){
                        e.printStackTrace();
//异常 回滚所有事务
                        for (TransactionStatus transactionStatus:transactionStatuses) {
                            transactionStatus.setRollbackOnly();
                        }

                    }


                    latch.countDown();
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }



        //更新外呼任务客户总数 customerCnt、未分配客户数 notDistributeCnt、未拨打数 not_call_cnt
        task.setCustomerCnt(task.getCustomerCnt()+total);
        task.setNotDistributeCnt(task.getNotDistributeCnt()+total);
        task.setNotCallCnt(task.getNotCallCnt()+total);
        taskService.updateById(task);
        return "成功导入:"+ total +"条记录<br/>"+result;
    }

3、整体类

package com.ps.uzkefu.apps.crm.service.impl;

import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ps.uzkefu.apps.callout.entity.Task;
import com.ps.uzkefu.apps.callout.service.TaskService;
import com.ps.uzkefu.apps.crm.entity.Customer;
import com.ps.uzkefu.apps.crm.entity.CustomerRecord;
import com.ps.uzkefu.apps.crm.mapper.CustomerDao;
import com.ps.uzkefu.apps.crm.service.CustomerRecordService;
import com.ps.uzkefu.apps.crm.service.CustomerService;
import com.ps.uzkefu.apps.oms.account.entity.DefinedField;
import com.ps.uzkefu.apps.oms.account.entity.DefinedFieldOption;
import com.ps.uzkefu.apps.oms.account.entity.DefinedFieldValue;
import com.ps.uzkefu.apps.oms.account.service.DefinedFieldOptionService;
import com.ps.uzkefu.apps.oms.account.service.DefinedFieldService;
import com.ps.uzkefu.apps.oms.account.service.DefinedFieldValueService;
import com.ps.uzkefu.apps.oms.account.service.UserService;
import com.ps.uzkefu.base.BaseServiceImpl;
import com.ps.uzkefu.common.ExecutionContext;
import com.ps.uzkefu.common.UkConstant;
import com.ps.uzkefu.util.DateUtil;
import com.ps.uzkefu.util.ExcelTemplateExportUtil;
import com.ps.uzkefu.util.ThreadPoolUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.executor.BatchExecutorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.sql.BatchUpdateException;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author WuZhiWei
 * @since 2018-07-06
 */
@Transactional(rollbackFor = {Exception.class})
@Service
public class CustomerServiceImpl extends BaseServiceImpl<CustomerDao, Customer> implements CustomerService {

    @Autowired
    private DefinedFieldValueService definedFieldValueService;
    @Autowired
    private DefinedFieldService definedFieldService;
    @Autowired
    private DefinedFieldOptionService definedFieldOptionService;

    @Autowired
    private CustomerRecordService customerRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private TaskService taskService;
    @
  • 9
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 20
    评论
### 回答1: 对于这个问题,我可以回答。在 Spring Boot 中,多线程事务回滚可以通过使用 @Transactional 注解来实现。在多线程环境下,需要使用 TransactionTemplate 来控制事务的边界。如果一个线程抛出异常,所有参与到这个事务中的线程都会回滚。 ### 回答2: 在Spring Boot中,我们可以使用多线程执行一些并发操作,并在其中进行事务管理。但是,默认情况下,多线程事务是无法进行回滚的。 要实现多线程事务回滚,我们可以采用以下两种方式: 1. 基于编程式事务管理: 在方法中使用编程式事务管理器,并手动在异常发生时进行事务回滚。首先,我们需要在方法上加上`@Transactional`注解来启用事务管理。然后,在方法体中,我们可以通过获取当前事务管理器的实例,并通过它来进行事务管理。当出现异常时,我们可以使用`TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()`方法来进行事务回滚。这样,当任何一个线程中的事务发生异常时,整个事务都会回滚。 2. 基于注解式事务管理: 在方法上加上`@Async`注解,并结合`@Transactional`注解来启用异步事务管理。首先,我们需要在`@Configuration`类中使用`@EnableAsync`注解启用异步支持。然后,在方法上加上`@Async`注解来开启异步执行。接着,我们需要在方法上同时添加`@Transactional`注解来启用事务管理。这样,当方法执行时,Spring会将其放入一个独立的线程中并异步执行,同时也会在子线程中开启一个新的事务。当发生异常时,整个子线程中的事务都会进行回滚。 总结起来,实现Spring Boot多线程事务回滚可以通过编程式事务管理和注解式事务管理两种方式来实现。无论使用哪种方式,我们都需要确保在事务异常发生时进行事务回滚,以保证数据的一致性和完整性。 ### 回答3: 在Spring Boot中,多线程事务回滚可以通过使用@Transactional注解来实现。事务是由Spring的事务管理器管理的,它可以管理多个线程同时进行的数据库操作。 通过在方法上添加@Transactional注解,可以将该方法纳入到一个事务中。当事务中的任何一个操作失败时,整个事务都会被回滚,即所有之前的操作都会撤销。 在多线程环境下,如果多个线程同时操作同一个数据库表,通过@Transactional注解可以确保他们在同一个事务中进行操作。当其中一个线程操作失败时,整个事务将会被回滚,所有线程的操作都会被撤销。 为了实现多线程事务回滚,需要确保所有的数据库操作都在同一个事务中执行。这可以通过在多线程方法的外部添加@Transactional注解来实现。当方法被调用时,将会启动一个新的事务,并将所有线程的操作添加到这个事务中。 需要注意的是,在使用多线程事务时,事务的隔离级别也非常重要。可以根据具体需求来选择适当的隔离级别。在默认情况下,Spring Boot使用的是数据库的默认隔离级别。 总之,使用Spring Boot的@Transactional注解可以很方便地实现多线程事务回滚。通过将所有操作添加到同一个事务中,可以在任何一个操作失败时回滚整个事务。而在多线程环境下,则需要保证所有线程的操作都在同一个事务中执行,以确保事务的一致性。
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值