현재 모바일 청첩장을 생성할 때, 이미지가 최대 14장이 저장되어
모바일 청첩장을 생성하는 요청 API의 응답속도가 매우 느리다.
이미지를 비동기 처리를 통해 해결하기로 했다.
@Configuration
public class AsyncConfig {
@Bean(name = "imageUploadExecutor")
public Executor imageUploadExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadGroupName("imageUploadExecutor");
executor.setCorePoolSize(14);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(50);
executor.initialize();
return executor;
}
}
Config 파일을 추가해주고
...
**@EnableAsync**
...
public class InvitationApplication {
public static void main(String[] args) {
SpringApplication.run(InvitationApplication.class, args);
}
}
@Async("imageUploadExecutor")
@Transactional
public CompletableFuture<Map<ImageUploadKey,String>> saveFileAsync(MultipartFile multipartFile) {
CompletableFuture<Map<ImageUploadKey, String>> future = new CompletableFuture<>();
future.complete(this.saveFile(multipartFile));
return future;
}
기존 AWS S3에 이미지 저장을 수행하는 s3UploadService 에 CompletableFuture 타입을 반환하는 메서드를 추가했다.
@Transactional
public void save(List<MultipartFile> gallery, Invitation invitation) throws IOException {
Long sequence = 1L;
List<CompletableFuture<Map<ImageUploadKey, String>>> futures = gallery.stream()
.map(s3UploadService::saveFileAsync)
.toList();
for (CompletableFuture<Map<ImageUploadKey, String>> future : futures) {
Map<ImageUploadKey, String> savedFileMap = future.join();
if (savedFileMap != null) {
String originFileName = savedFileMap.get(ORIGIN_FILE_NAME);
String storeFileName = savedFileMap.get(STORE_FILE_NAME);
String savedUrlPath = savedFileMap.get(IMAGE_URL);
Gallery newGallery = new Gallery(originFileName, storeFileName, sequence++, savedUrlPath);
newGallery.setInvitation(invitation);
}
}
}