在之前的Java多线程导入Excel示例中演示了如何通过多线程的方式导入Excel,下面我们再来看下怎么通过多线程的方式导出Excel
还是直接上代码
首先是Controller
import com.sakura.base.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@RestController
@RequestMapping("/excel")
public class ExcelController {@Autowiredprivate ExcelService excelService;@GetMapping("/export")public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {excelService.exportExcel(request, response);}
}
然后Service
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public interface ExcelService {void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception;}
还有ServiceImpl
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sakura.base.entity.User;
import com.sakura.base.mapper.UserMapper;
import com.sakura.base.service.ExcelService;
import lombok.extern.java.Log;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;@Service
@Log
public class ExcelServiceImpl implements ExcelService {@Autowiredprivate UserMapper userMapper;@Overridepublic void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {// 创建一个Excel文件,放在这里可以不用手动关闭流try (Workbook workbook = new XSSFWorkbook()) {// 创建一个Excel页Sheet sheet = workbook.createSheet("users");// 创建表头Row headerRow = sheet.createRow(0);// 给表头创建单元格并赋值headerRow.createCell(0).setCellValue("姓名");headerRow.createCell(1).setCellValue("手机号");headerRow.createCell(2).setCellValue("导出日期");// 每次处理的数据量,大家可以自己调整,比如每次处理1000条int batchSize = 5;// 最大线程数,大家可以自己调整,根据自己服务器性能来调整int maxThreads = 3;// 创建线程池ExecutorService executorService = Executors.newFixedThreadPool(maxThreads);// 查询总记录数int totalCount = userMapper.selectCount(null);// 计算总批次int totalBatches = (int) Math.ceil((double) totalCount / batchSize);// 分批次导出数据for (int i = 0; i < totalBatches; i++) {int offset = i * batchSize;// 提交任务executorService.execute(new ExcelWriterTask(sheet, offset, batchSize));}// 关闭线程池executorService.shutdown();executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); // 等待所有任务执行完毕 Long.MAX_VALUE为超时时间,可以自由设置response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "attachment;filename=users.xlsx");workbook.write(response.getOutputStream());} catch (Exception e) {e.printStackTrace();}}private class ExcelWriterTask implements Runnable {private Sheet sheet;private int offset;private int batchSize;public ExcelWriterTask(Sheet sheet, int offset, int batchSize) {this.sheet = sheet;this.offset = offset;this.batchSize = batchSize;}@Overridepublic void run() {// 测试用,模拟处理数据的耗时// _________________________________________try {Thread.sleep(2000);} catch (InterruptedException e) {throw new RuntimeException(e);}// _________________________________________// 查询数据List<User> users = userMapper.selectList(new QueryWrapper<User>().orderByAsc("id").last("limit " + offset + ", " + batchSize));// 这里要注意,写入数据的时候需要同步写入,不然会出现覆盖等问题synchronized (sheet) {int rowNum = sheet.getLastRowNum();for (User user : users) {Row row = sheet.createRow(++rowNum);row.createCell(0).setCellValue(user.getName());row.createCell(1).setCellValue(user.getPhoneNumber());// 加个日期是为了好验证多线程导出的结构row.createCell(2).setCellValue(new Date().toString());}}}}}
实体类User这里也不贴了
poi的jar包
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency>
测试一下接口
看下导出的Excel里面的数据,一样的,因为我限制了每次处理的数据为5条,同时最多有3个线程,所以可以看到同一时间段导出的数据为15条
这里也有个问题,细心的人可能已经发现了,在写入的时候其实我加了synchronized关键字,这也导致了所有线程都必须等待其他线程完成写入操作后才能进行自己的写入操作,从而将并发写入转变为了串行写入,这似乎与多线程的使用相违背,这这种想法是对的,但是目前我也没想到更好的方法来控制多个线程同时写入的问题,当然这样写还是有用上多线程加快处理速度的特性的,毕竟在数据处理阶段,本来一条数据就要处理2秒,现在3个线程2秒可以同时处理3条数据,至于写入的那点时间其实可以忽略不计。