1.为了提高我们接口的响应速度,我们可以开多个线程,并行处理,比如我们要大批量写入数据到数据库
@Autowired
private ThreadPoolExecutor executor;
@Autowired
private PlatformTransactionManager transactionManager;
private List<TransactionStatus> transactionStatuses = Collections.synchronizedList(new ArrayList<TransactionStatus>());
@Override
public void tx2PC() {
List<Integer> addList = new ArrayList<>();
for (int i = 0; i < 2000; i++) {
addList.add(i);
}
List<List<Integer>> partitions = Lists.partition(addList, 800);
AtomicBoolean isError = new AtomicBoolean(false);
List<Thread> unfinishedList = new ArrayList<>();
AtomicInteger cur = new AtomicInteger(1);
int totalSize = partitions.size();
CompletableFuture<Void> future = CompletableFuture.allOf(
partitions.stream().map(partition ->
CompletableFuture.runAsync(() -> {
TransactionStatus transactionStatus = beginNewTransaction();
int curInt = cur.getAndIncrement();
try {
log.info("当前是第{}个线程开始启动,线程名={}", curInt, Thread.currentThread().getName());
synchronized (unfinishedList) {
unfinishedList.add(Thread.currentThread());
}
log.info("当前是第{}个线程已加入队列,开始休眠,线程名={}", curInt, Thread.currentThread().getName());
insert2(1);
insert3(1);
notifyAllThread(unfinishedList, totalSize, false);
LockSupport.park();
if (isError.get()) {
log.info("当前是第{}个线程回滚,线程名={}", curInt, Thread.currentThread().getName());
transactionManager.rollback(transactionStatus);
} else {
log.info("当前是第{}个线程提交,线程名={}", curInt, Thread.currentThread().getName());
transactionManager.commit(transactionStatus);
}
} catch (Exception e) {
log.error("当前是第{}个线程出现异常,线程名={}", curInt, Thread.currentThread().getName(), e);
transactionManager.rollback(transactionStatus);
e.printStackTrace();
isError.set(true);
notifyAllThread(unfinishedList, totalSize, true);
}
}, executor)).toArray(CompletableFuture[]::new));
future.join();
}
private void notifyAllThread(List<Thread> unfinishedList, int totalSize, boolean isForce) {
if (isForce || unfinishedList.size() >= totalSize) {
log.info("唤醒当前所有休眠线程,线程数={},总线程数={},是否强制={}", unfinishedList.size(), totalSize, isForce);
for (Thread thread : unfinishedList) {
log.info("当前线程={}被唤醒", thread.getName());
LockSupport.unpark(thread);
}
}
}
private TransactionStatus beginNewTransaction() {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus status = transactionManager.getTransaction(def);
return status;
}