大数据量操作时,多线程提升系统性能,可以利用线程池和CountDownLatch,多线程并发处理批量数据,实现多线程事务回滚,事务补偿。
package com.example.springbootdemo.threadTransaction.service.impl;
import com.example.springbootdemo.threadTransaction.mapping.TxUserMapper;
import com.example.springbootdemo.threadTransaction.service.TxUpdateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@Service
@Slf4j
public class TxUpdateServiceImpl implements TxUpdateService {
@Autowired
private TxUserMapper userMapper;
@Autowired
private PlatformTransactionManager transactionManager;
@Override
public boolean update(Integer id, String name) {
// 线程计数器
CountDownLatch threadLatch = new CountDownLatch(3);
// 线程池
ExecutorService pool = Executors.newFixedThreadPool(3);
// 异常监测
AtomicBoolean isError = new AtomicBoolean(false);
AtomicInteger integer = new AtomicInteger(0);
// 模拟3批次的数据处理
for (int i = 0; i < 3; i++) {
pool.execute(() -> {
try {
final int get = integer.addAndGet(1);
boolean doUpdate = doUpdate(id + get, name, isError, threadLatch);
} catch (Exception e) {
log.error("出错啦", e);
isError.set(true);
}
});
}
try {
threadLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();
return true;
}
public boolean doUpdate(Integer id, String name, AtomicBoolean isError, CountDownLatch threadLatch) throws InterruptedException {
Integer update = null;
// 开启事务
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus status = transactionManager.getTransaction(def);
try {
// 执行sql
update = userMapper.update(id, name);
// 模拟数据处理耗时
Thread.sleep(id * 1000);
// 模拟处理中出现异常
if (id == 1) {
isError.set(true);
}
} finally {
// 标识线程执行完毕
threadLatch.countDown();
}
// 等待所有线程执行完毕
threadLatch.await();
if (isError.get()) {
log.info("线程:{}检测到异常,事务回滚", Thread.currentThread().getName());
transactionManager.rollback(status);
} else {
log.info("线程:{}正常执行完毕,事务提交", Thread.currentThread().getName());
transactionManager.commit(status);
}
return update > 0;
}
}
数据库修改前
写一个接口,模拟网络请求,在执行中出错所有事务回滚,数据库数据无变化
修改标识出错的代码,保证所有线程正常执行
if (id == 10) {
isError.set(true);
}
模拟网络请求,在执行中正常执行,所有事务提交,数据库数据已变
修改后的数据库数据