解决多线程事务问题

spring的声明式事务在使用多线程时,并不会生效。可以使用spring提供的编程式事务解决。

核心思路是为每一个线程都开辟一个事务。

第一步:使用spring提供的编程式事务

 @Autowired
    private TransactionTemplate transactionTemplate;

第二步:在代码逻辑处写入业务逻辑

 transactionTemplate.execute(

       new TransactionCallbackWithoutResult(){
        @Override
   protected void doInTransactionWithoutResult(TransactionStatus status) {

    //代码逻辑
  userMapper.insertBatch(list);
            int m=1/0;
                        
        }
            }

 );

第三步:将上面的放入多线程中,线程池和new 线程都可以

executor.execute(() -> {
                    transactionTemplate.execute(

                            new TransactionCallbackWithoutResult(){
                                @Override
                                protected void doInTransactionWithoutResult(TransactionStatus status) {
                                    userMapper.insertBatch(list);
                                    int m=1/0;
  
 
                                }
                            }


                    );


                });

亲测有效,至于网上的提供的一些 生成线程屏障的方法 试了下不行,也不知道是不是我的问题。

demo供参考

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Override
    public Result batchAdd(User... user) {


        if (user.length == 0) {
            throw new ServiceException("新增参数不能为空");
        }

        log.info("准备执行新增,当前需要新增数量为{}", user.length);
        if (user.length > 10) {

            int coreSize = user.length / 20 + 1;
            int size = user.length;

            //切片 每20个一次

            int batch = size % 20 == 0 ? size / 20 : size / 20 + 1;

            ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, coreSize, 5, TimeUnit.SECONDS, new LinkedBlockingQueue());


            log.info("线程池创建完毕,准备执行认为,线程数量为{}", coreSize);
          

            List users = Arrays.asList(user);
            for (int i = 0; i < batch; i++) {
                int end = (i + 1) * 20;
                log.info("第{}个集合", i + 1);

                if (end > size) {
                    end = size;
                }

                List list = users.subList(i * 20, end);
                log.info("集合大小为{}", list.size());


                int finalI = i;

                executor.execute(() -> {
                    transactionTemplate.execute(

                            new TransactionCallbackWithoutResult(){
                                @Override
                                protected void doInTransactionWithoutResult(TransactionStatus status) {
                                    userMapper.insertBatch(list);
                                    int m=1/0;
                                    List ids = list.stream().map(User::getId).collect(Collectors.toList());
                                    log.info("新增成功用户成功,主键为{},当前线程为{}", ids, Thread.currentThread().getName());
                                    log.info("我执行了{}", finalI);
                                }
                            }


                    );


                });

            }



            executor.shutdown();
            log.info("批量增加完毕,线程池关闭");


        } else {

            if (saveBatch(Arrays.asList(user))) {
//                int a= 1/0;
                log.info("新增完成");
            } else {
                log.error("新增失败");
            }


        }


        return new Result();
    }

    @Override
    public Result getUserList(User user) {

        LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User::getId, User::getUserName, User::getPhone);
        wrapper.like(user.getUserName() != null, User::getUserName, user.getUserName())
                .eq(user.getPhone() != null, User::getPhone, user.getPhone());
        List users = userMapper.selectList(wrapper);

        return new Result(users);
    }
}

更新一下内容:

当时是为了同步数据,适合某一线同步失败,只回滚当前线程的数据 。发现评论有需要回滚全部的,给出了思路后,小伙伴依然有疑问,抽空写了个demo,供大家参考。使用的依旧是编程式事务,核心思路类似二阶段提交,生产中并不建议这样使用,线程之间的同步也需要耗费很多资源的,不要为了使用多线程而用。另外发现,批处理也可以做到这两种回滚,而且貌似更简单,有兴趣的可以自行研究下。

    public Result batchAdd(User... user) {


        if (user.length == 0) {
            throw new ServiceException("新增参数不能为空");
        }

        log.info("准备执行新增,当前需要新增数量为{}", user.length);
        if (user.length > 10) {

            int coreSize = user.length / 5+ 1;
            int size = user.length;

            //切片 每20个一次

            int batch = size % 5== 0 ? size / 5: size / 5 + 1;

            ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, coreSize, 5, TimeUnit.SECONDS, new LinkedBlockingQueue());


            log.info("线程池创建完毕,准备执行认为,线程数量为{}", coreSize);
          
            CountDownLatch latch = new CountDownLatch(batch);

            AtomicBoolean isError = new AtomicBoolean(false);

            List users = Arrays.asList(user);
            for (int i = 0; i < batch; i++) {
                int end = (i + 1) * 5;
                log.info("第{}个集合", i + 1);

                if (end > size) {
                    end = size;
                }

                List list = users.subList(i * 5, end);
                log.info("集合大小为{}", list.size());


                int finalI = i;

                executor.execute(() -> {
                    transactionTemplate.execute(

                    new TransactionCallbackWithoutResult(){
                                @Override
                                protected void doInTransactionWithoutResult(TransactionStatus status) {

                                    try {
                                        saveBatch(list);


                                        List ids = list.stream().map(User::getId).collect(Collectors.toList());
                                        log.info("新增成功用户成功,主键为{},当前线程为{}", ids, Thread.currentThread().getName());
                                        log.info("我执行了{}", finalI);
                                       if(Thread.currentThread().getName().equals("pool-1-thread-2")){
                                            int m=1/0;
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        System.out.println("ssss");
                                        isError.set(true);
                                    } finally {
                                        System.out.println("r");
                                        latch.countDown();
                                    }


                                    try {
                                        latch.await();
                                        if (isError.get()){
                                            status.setRollbackOnly();
                                        }
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                        throw new RuntimeException("出错啦");
                                    }


                                }
                            }


                    );


                });





            }

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

            executor.shutdown();
            log.info("批量增加完毕,线程池关闭");


        } 


        return new Result();
    }

你可能感兴趣的:(日常,java,开发语言)