package com.ruoyi.common.core.service; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.pagehelper.Page; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.core.page.PageDomain; import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.utils.PageUtils; import com.ruoyi.common.utils.file.DownloadExportUtil; import com.ruoyi.common.utils.poi.ExcelUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.util.List; import java.util.function.Function; /** * 通用服务 */ @Service public abstract class BaseService,T> extends ServiceImpl { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private RedisCache redisCache; /** * 通用异步导出方法 * * @param exportKey 导出任务的唯一标识 * @param sheetName 工作表名称 * @param dataFetcher 数据获取函数,接受分页参数返回数据列表 */ @Async public void export(Class c, String exportKey, String sheetName, Function> dataFetcher) { String fileName = ExcelUtil.encodeFileName(sheetName); // 设置当前任务为“下载中”状态 DownloadExportUtil.deleteDownloadFile(redisCache, exportKey, "0"); try { // 执行导出并获取文件名 fileName = exportData( c,fileName, sheetName, dataFetcher); // 设置下载完成状态 DownloadExportUtil.setDownloadFile(redisCache, exportKey, fileName); logger.info("Export completed for key: {}, file: {}", exportKey, fileName); } catch (Exception e) { logger.error("Export failed for key: {}, error: {}", exportKey, e.getMessage(), e); DownloadExportUtil.deleteDownloadFile(redisCache, exportKey, "1"); // 设置失败状态 throw e; } } /** * 通用分页导出逻辑 * * @param fileName 文件名 * @param sheetName 工作表名称 * @param dataFetcher 数据获取函数 * @return 导出后的文件名 */ protected String exportData(Class c, String fileName, String sheetName, Function> dataFetcher) { ExcelUtil excelUtil = new ExcelUtil<>(c); excelUtil.initialize(sheetName, null, Excel.Type.EXPORT); int pageNum = 1; boolean hasMoreData = true; while (hasMoreData) { List pageData = dataFetcher.apply(pageNum); if (pageData != null && !pageData.isEmpty()) { // 导出当前页的数据 excelUtil.exportExcel(pageData); pageNum++; } else { // 没有数据时退出 hasMoreData = false; } } excelUtil.finishExport(fileName); return fileName; } }