@Override
@Transactional
public int upExcel(MultipartFile file, Integer createStaff) throws IOException {
List<String[]> excelList = ExcelUtil.readExcel(file);
/**
* 修改了工具类,在工具类中去掉了每张sheet页的表头行
* 原功能是工具类中不做处理,在此处去掉第一张sheet页的第一行
*/
// excelFile.remove(0);
int threadCount = 30;// 一个线程处理20条数据
int listSize = excelList.size() ;
int runThreadSize = (listSize / threadCount)+1 ;
final CountDownLatch countDownLatch = new CountDownLatch(runThreadSize); //计数器闭锁
ExecutorService executor = Executors.newCachedThreadPool();
List<String[]> newlist = null;
AtomicInteger successedNum = new AtomicInteger(0);
try {
for (int i = 0; i < runThreadSize; i++) {
//设置索引
if ((i + 1) == runThreadSize) {
int startIndex;
startIndex = (i * threadCount);
int endIndex = excelList.size();
newlist = excelList.subList(startIndex, endIndex); // subList子列表: 部分元素的引用
} else {
int startIndex = (i * threadCount);
int endIndex = (i + 1) * threadCount;
newlist = excelList.subList(startIndex, endIndex);
}
final List<String[]> excelSubList = newlist;
executor.execute(new Thread() {
// @SneakyThrows
@Override
public void run() {
List<CustomerAllFieldDTO> customerList = new ArrayList<>();// 单个线程要插入的list
//填充数据
for (int i = 0; i < excelSubList.size(); i++) {
判断手机号是否有客户存在
List<CustomerValueDto> customerValueDtoList = customeInfoDao.getCustomerByPhone(excelSubList.get(i)[1]);
if(customerValueDtoList.size() > 0 && customerValueDtoList.get(0).getValue()==0){
continue;
};
CustomerAllFieldDTO customerAllFieldDTO = new CustomerAllFieldDTO();
customerAllFieldDTO.setCreateStaff(createStaff); // 创建人ID
customerAllFieldDTO.setCustomerName(excelSubList.get(i)[0]); // 客户姓名
customerAllFieldDTO.setCustomerPhone(excelSubList.get(i)[1]); // 客户号码
customerList.add(customerAllFieldDTO);
}
//执行插入和统计
try {
int inserted = customeInfoDao.insertAllCustomer(customerList);
synchronized (successedNum){
successedNum.addAndGet(inserted); // 使用原子操作进行累加inserted;
}
} catch (Exception e){
e.printStackTrace();
// throw new Exception("插入失败"); //不在这里抛
}finally {
countDownLatch.countDown();
}
} //没有提前返回 是报异常了
} );
}
}catch (Exception e){
e.printStackTrace();
return 0;
} finally {
try {
countDownLatch.await(); // 确保主线程会等待所有线程完成后再返回
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
return successedNum.intValue(); //finally块内部的return语句会覆盖try-catch块内部的任何其他return语句。这可能导致意外的行为,例如方法会过早地返回。
}
}
DAO层
List<CustomerValueDto> getCustomerByPhone(@Param("customerPhone") String customerPhone);
<select id="getCustomerByPhone" resultType="com.gccloud.gc.csp.pbx.cloud.cc.custom.dto.CustomerValueDto">
select customer_id as `custId`,IS_DEL as `value` from gc_ccsp_customer where customer_phone=#{customerPhone}
</select>