package com.chinautil.preview.service.impl;
import com.chinautil.preview.mapper.UserMapper;
import com.chinautil.preview.pojo.User;
import com.chinautil.preview.service.FileDownService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FileDownServiceImpl extends ServiceImpl<UserMapper, User> implements FileDownService {
@Resource
private UserMapper userMapper;
@Override
public void downloadFile(String request, HttpServletResponse response) {
//创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
long startTime = System.currentTimeMillis();
try {
OutputStream outputStream = response.getOutputStream();
ExcelWriter writer = EasyExcel.write().build();
List<User> users = new ArrayList<>;
int count = userMapper.countUser(request);
int pagesize = (count / 2000) + (count % 2000 > 0 ? 1 : 0);
CountDownLatch countDownLatch = new CountDownLatch(pagesize);
boolean hasnext = true;
int pagenum1 = 1;
while (
hasnext
) {
pagesize--;
int page = pagenum1;
executorService.execute(() -> {
try {
log.info("当前线程:{},批次{}", Thread.currentThread().getName(), page);
Thread.sleep(300);
PageInfo<User> pageInfo = PageHelper.startPage(page, 2000).doSelectPageInfo(() -> UserMapper.selectUser(request));
List<User> list = pageInfo.getList();
users.addAll(list);
} catch (Exception e) {
log.error("数据查询异常:{}, 批次:{}", e.getMessage(), page);
} finally {
countDownLatch.countDown();
}
});
if (pagesize == 0) {
hasnext = false;
} else {
hasnext = true;
}
page++;
}
countDownLatch.await();
WriteSheet writeSheet = EasyExcel.writeSheet(1, "WriteSheet").build();
writer.write(writeSheet, users);
excelWriter.finish();
outputStream.flush();
response.getOutputStream().close();
long endTime = System.currentTimeMillis();
log.info("需要时间================" + (endTime - startTime));
} catch (Exception e) {
log.error("Exception", e.getMessage());
}
}
}
多线程分页导出数据
最新推荐文章于 2024-07-02 11:24:49 发布