260708_02_ENH: 파일 업로드 시 pdf 변환 async로 분리
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package com.kri.gwcf.review.back.config;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class AsyncConfig {
|
||||
|
||||
@Bean(name = "pdfConvertTaskExecutor")
|
||||
public Executor pdfConvertTaskExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(1);
|
||||
executor.setMaxPoolSize(1);
|
||||
executor.setQueueCapacity(100);
|
||||
executor.setThreadNamePrefix("pdf-convert-");
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.kri.gwcf.review.back.service;
|
||||
|
||||
import com.kri.common.feature.util.StringUtil;
|
||||
import com.kri.gwcf.review.back.persistence.entity.TPerformanceReviewEntity;
|
||||
import com.kri.gwcf.review.back.persistence.repository.PerformanceReviewRepository;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ReviewPdfConvertService {
|
||||
|
||||
private final PerformanceReviewRepository performanceReviewRepository;
|
||||
|
||||
@Value("${kri.file.pdf-converter-command:soffice}")
|
||||
private String pdfConverterCommand;
|
||||
|
||||
@Async("pdfConvertTaskExecutor")
|
||||
public void convertReviewFileToPdf(
|
||||
Integer performanceId,
|
||||
Integer reviewType,
|
||||
String userId,
|
||||
String uploadFileName,
|
||||
Path source,
|
||||
Path dir
|
||||
) {
|
||||
String pdfFileName = convertToPdfIfPossible(source, dir);
|
||||
if (StringUtil.isNullOrBlank(pdfFileName)) {
|
||||
log.warn(
|
||||
"Review PDF conversion failed. performanceId={}, reviewType={}, userId={}, uploadFileName={}",
|
||||
performanceId,
|
||||
reviewType,
|
||||
userId,
|
||||
uploadFileName
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
performanceReviewRepository
|
||||
.findByIdPerformanceIdAndIdReviewTypeAndIdRegUser(performanceId, reviewType, userId)
|
||||
.filter(entity -> uploadFileName.equals(entity.getUploadFileName()))
|
||||
.ifPresentOrElse(
|
||||
entity -> updatePdfConvertResult(entity, pdfFileName),
|
||||
() -> log.info(
|
||||
"Skipped stale review PDF conversion result. performanceId={}, reviewType={}, userId={}, uploadFileName={}, pdfFileName={}",
|
||||
performanceId,
|
||||
reviewType,
|
||||
userId,
|
||||
uploadFileName,
|
||||
pdfFileName
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private void updatePdfConvertResult(TPerformanceReviewEntity entity, String pdfFileName) {
|
||||
entity.setPdfConvert(true);
|
||||
entity.setPdfFileName(pdfFileName);
|
||||
performanceReviewRepository.save(entity);
|
||||
}
|
||||
|
||||
private String convertToPdfIfPossible(Path source, Path dir) {
|
||||
String extension = extractExtension(source.getFileName().toString()).toLowerCase();
|
||||
Set<String> targets = new HashSet<>(Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx"));
|
||||
if (!targets.contains(extension)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
try {
|
||||
Process process = new ProcessBuilder(
|
||||
pdfConverterCommand,
|
||||
"--headless",
|
||||
"--convert-to",
|
||||
"pdf",
|
||||
"--outdir",
|
||||
dir.toString(),
|
||||
source.toString()
|
||||
).redirectErrorStream(true).start();
|
||||
|
||||
boolean finished = process.waitFor(300, TimeUnit.SECONDS);
|
||||
if (!finished || process.exitValue() != 0) {
|
||||
process.destroyForcibly();
|
||||
return "";
|
||||
}
|
||||
|
||||
String baseName = stripExtension(source.getFileName().toString());
|
||||
Path pdf = dir.resolve(baseName + ".pdf").normalize();
|
||||
return Files.exists(pdf) ? pdf.getFileName().toString() : "";
|
||||
} catch (Exception e) {
|
||||
log.warn("Review PDF conversion error. source={}", source, e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private String stripExtension(String fileName) {
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
return dot > 0 ? fileName.substring(0, dot) : fileName;
|
||||
}
|
||||
|
||||
private String extractExtension(String fileName) {
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
return dot >= 0 ? fileName.substring(dot) : "";
|
||||
}
|
||||
}
|
||||
@@ -16,15 +16,15 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.PathResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@@ -33,9 +33,7 @@ public class ReviewService extends AbstractFileService {
|
||||
|
||||
private final PerformanceReviewRepository performanceReviewRepository;
|
||||
private final FileStorageProperties fileStorageProperties;
|
||||
|
||||
@Value("${kri.file.pdf-converter-command:soffice}")
|
||||
private String pdfConverterCommand;
|
||||
private final ReviewPdfConvertService reviewPdfConvertService;
|
||||
|
||||
@Override
|
||||
protected Path getBaseDir() {
|
||||
@@ -139,9 +137,7 @@ public class ReviewService extends AbstractFileService {
|
||||
saveFile(dir, file, uploadFileName);
|
||||
Path uploadPath = dir.resolve(uploadFileName).normalize();
|
||||
|
||||
String pdfFileName = isPdf(uploadFileName)
|
||||
? uploadFileName
|
||||
: convertToPdfIfPossible(uploadPath, dir);
|
||||
String pdfFileName = isPdf(uploadFileName) ? uploadFileName : "";
|
||||
boolean pdfConvert = StringUtil.hasText(pdfFileName);
|
||||
|
||||
TPerformanceReviewEntity entity = performanceReviewRepository
|
||||
@@ -167,7 +163,12 @@ public class ReviewService extends AbstractFileService {
|
||||
entity.setModDt(now);
|
||||
}
|
||||
|
||||
return PerformanceReviewDto.from(performanceReviewRepository.save(entity));
|
||||
TPerformanceReviewEntity saved = performanceReviewRepository.save(entity);
|
||||
if (!pdfConvert && isPdfConvertTarget(uploadFileName)) {
|
||||
convertPdfAfterCommit(performanceId, reviewType, userId, uploadFileName, uploadPath, dir);
|
||||
}
|
||||
|
||||
return PerformanceReviewDto.from(saved);
|
||||
} catch (IOException e) {
|
||||
throw BusinessException.internalError("REVIEW_FILE_SAVE_FAILED", "평가/모니터링 파일 저장 중 오류가 발생했습니다.");
|
||||
}
|
||||
@@ -177,6 +178,36 @@ public class ReviewService extends AbstractFileService {
|
||||
return PerformanceReviewDto.from(getReviewEntity(performanceId, reviewType, userId));
|
||||
}
|
||||
|
||||
private void convertPdfAfterCommit(
|
||||
Integer performanceId,
|
||||
Integer reviewType,
|
||||
String userId,
|
||||
String uploadFileName,
|
||||
Path uploadPath,
|
||||
Path dir
|
||||
) {
|
||||
Runnable task = () -> reviewPdfConvertService.convertReviewFileToPdf(
|
||||
performanceId,
|
||||
reviewType,
|
||||
userId,
|
||||
uploadFileName,
|
||||
uploadPath,
|
||||
dir
|
||||
);
|
||||
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
task.run();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
task.run();
|
||||
}
|
||||
|
||||
public PathResource getOriginalFileResource(Integer performanceId, Integer reviewType, String userId) {
|
||||
TPerformanceReviewEntity entity = getReviewEntity(performanceId, reviewType, userId);
|
||||
return toResource(reviewDir(performanceId, reviewType).resolve(entity.getUploadFileName()));
|
||||
@@ -303,38 +334,6 @@ public class ReviewService extends AbstractFileService {
|
||||
.normalize();
|
||||
}
|
||||
|
||||
private String convertToPdfIfPossible(Path source, Path dir) {
|
||||
String extension = extractExtension(source.getFileName().toString()).toLowerCase();
|
||||
Set<String> targets = new HashSet<>(Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx"));
|
||||
if (!targets.contains(extension)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
try {
|
||||
Process process = new ProcessBuilder(
|
||||
pdfConverterCommand,
|
||||
"--headless",
|
||||
"--convert-to",
|
||||
"pdf",
|
||||
"--outdir",
|
||||
dir.toString(),
|
||||
source.toString()
|
||||
).redirectErrorStream(true).start();
|
||||
|
||||
boolean finished = process.waitFor(60, TimeUnit.SECONDS);
|
||||
if (!finished || process.exitValue() != 0) {
|
||||
process.destroyForcibly();
|
||||
return "";
|
||||
}
|
||||
|
||||
String baseName = stripExtension(source.getFileName().toString());
|
||||
Path pdf = dir.resolve(baseName + ".pdf").normalize();
|
||||
return Files.exists(pdf) ? pdf.getFileName().toString() : "";
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private String stripExtension(String fileName) {
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
return dot > 0 ? fileName.substring(0, dot) : fileName;
|
||||
@@ -344,6 +343,11 @@ public class ReviewService extends AbstractFileService {
|
||||
return ".pdf".equalsIgnoreCase(extractExtension(fileName));
|
||||
}
|
||||
|
||||
private boolean isPdfConvertTarget(String fileName) {
|
||||
String extension = extractExtension(fileName).toLowerCase();
|
||||
return Set.of(".docx", ".hwpx", ".hwp", ".pptx", ".xlsx").contains(extension);
|
||||
}
|
||||
|
||||
private String removeTimestampPrefix(String fileName) {
|
||||
if (StringUtil.isNullOrBlank(fileName)) {
|
||||
return fileName;
|
||||
|
||||
Reference in New Issue
Block a user