直接看代码,这是一个多线程生成库存同步任务的,事务控制为一个大的事务,回滚就全部线程的任务不提交全部回滚
PlatformTransactionManager transactionManager;
(rollbackFor = Exception.class, value = "transactionManagerMysql", propagation = Propagation.NESTED)
public void mainStockClear1() {
List<TransactionStatus> transactionStatuses = Collections.synchronizedList(new ArrayList<TransactionStatus>());
List<DO2oStockUpt> do2oStockUpts = new ArrayList<>();
AtomicInteger atomicInteger = new AtomicInteger(0);
for (int i = 0; i < 5; i++) {
DO2oStockUpt do2oStockUpt = new DO2oStockUpt();
do2oStockUpt.setOlshopid(1L);
do2oStockUpt.setTfid(1);
do2oStockUpt.setBusnoOnline("1");
do2oStockUpt.setStoreId("1");
do2oStockUpt.setNumiid("1");
do2oStockUpt.setSkuid("1");
do2oStockUpt.setWarecode("1");
do2oStockUpt.setWareqty(0L);
do2oStockUpt.setStatus(0);
do2oStockUpt.setUpdType(1);
do2oStockUpt.setIsMain(1);
do2oStockUpt.setCreatetime(new Date());
do2oStockUpt.setTfid(i);
do2oStockUpts.add(do2oStockUpt);
int finalI = i;
ThreadPoolService.asynchronousTask(()->{
try {
updateStudentsTransaction(transactionManager, transactionStatuses, do2oStockUpt, finalI);
} catch (Exception e) {
e.printStackTrace();
atomicInteger.addAndGet(1);
}
});
}
if (!transactionStatuses.isEmpty()) {
if (atomicInteger.get() != 0) {
transactionStatuses.forEach(s -> transactionManager.rollback(s));
} else {
transactionStatuses.forEach(s -> transactionManager.commit(s));
}
}
}
(rollbackFor = Exception.class, value = "transactionManagerMysql", propagation = Propagation.REQUIRES_NEW)
public void updateStudentsTransaction(PlatformTransactionManager transactionManager,
List<TransactionStatus> transactionStatuses,
DO2oStockUpt do2oStockUpt, Integer i) throws Exception{
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
transactionStatuses.add(status);
if (i != null && 2 == i) {
throw new Exception();
}
do2oStockUptMapper.insert(do2oStockUpt);
}
private