일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 다리 만들기
- Stack
- BufferedReader
- 그리디
- DP
- LIS
- 아스키코드
- 문자열
- 완전탐색
- Java
- 시뮬레이션
- 프로그래머스
- dfs
- BFS
- 빅데이터
- oracle
- 구현
- 브루트포스
- HashMap
- Queue
- 스택
- 백준
- 새벽코딩
- 알고리즘
- 백트래킹
- 다이나믹프로그래밍
- Python
- 탐색
- 배열
- SQL
- Today
- Total
새벽코딩
대용량 트래픽 핸들링 및 대용량 파일업로드 본문
1. 대용량 트래픽시 발생할 수 있는 다양한 문제점을 핸들링할 수 있어야 한다.
1) 로드밸런싱
로드밸런서를 두어 트래픽을 여러서버 또는 인스턴스로 분산시켜줍니다. 이렇게 하면 개별 서버가 과부하 상태에 빠지지 않고 트래픽을 분산처리할 수 있습니다.
2) 캐싱
정적 콘텐츠를 캐싱하여 동일한 요청에 대한 응답을 반복 생성하지 않고 캐시된 버전을 제공합니다. 예로 서버 실행시 캐시메모리에 공통코드나 공통메시지등을 미리 담아두어 사용자가 해당 서비스를 실행할때 서버까지가 아닌 캐시메모리의 데이터를 접근하여 빠른 처리를 해줄 수 있다.
3) 비동기 처리
요청을 동기적으로 처리하는 대신, 비동기 방식으로 처리하여 응답 지연을 최소화 하고 처리량을 향상시킬 수 있습니다. 이를 위해 메시지 큐(RabbitMQ) 시스템을 사용하거나 비동기 프로그래밍 모델을 직접 구현할 수 있습니다.
4) 데이터베이스 최적화
데이터베이스 쿼리를 최적화하고, 샤딩 또는 복제를 사용하여 데이터베이스 부하를 분산시켜야한다.
5) 수평 확장
서버 수를 늘려서 대용량 트래픽을 처리할 수 있습니다. 클라우드 서비스를 사용하여 필요에 따라 자동으로 서버를 확장하거나 축소하도록 설정할 수도 있습니다.
2. 대용량 파일 업로드시 핸들링 (JAVA)
1) 파일 업로드 라이브러리 사용
Java 웹 애플리케이션에서는 Apache COmmons FileUpload, Servlet 3.0 멀티파트 파일 업로드, Spring Framework의 MultipartFile등과 같은 라이브러리를 사용하여 파일업로드를 처리할 수 있다.
(필자의 경우 Spring Framework MultipartFile 라이브러리를 사용하여 파일업로드를 처리하였다.)
2) 메모리 버퍼 제한 설정
업로드할 파일이 대용량인 경우에는 서버의 메모리 부담을 줄이기 위해 업로드 버퍼크기를 적절하게 설정해주어야한다. 이를 통해 대용량 파일을 조각조각으로 나누어 메모리에 로드하므로 메모리부하를 최소화 할 수 있습니다.
1. SpringContext.xml 파일에서 CommonsMultipartResolver 빈을 설정하고 메모리 버퍼 크기를 지정한다.
- 업로드할 파일의 최대 크기를 설정한다 (이 값보다 큰 파일은 디스크에 임시로 저장된다)
- 메모리 버퍼 크기를 설정한다 (이 값 이하의 파일은 메모리에 저장된다)
<bean id="multipartResolver" class="org.springframwork.web.multipart.common.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/> <!-- 10MB -->
<property name="maxInMemorySize" value="10240"/> <!-- 10KB -->
</bean>
2. 컨트롤러에서 파일 업로드 처리
Bean등록을 하였다면 Spring Controller에서 파일 업로드 처리를 할 수 있다. MultipartFile 객체를 사용하여 업로드된 파일을 처리합니다.
import org.springframework.web.multipart.MultipartFile;
// ...
@RequestMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// 파일 처리 코드
// ...
} catch (IOException e) {
e.printStackTrace();
// 예외 처리
}
}
return "redirect:/success"; // 파일 업로드 완료 후 리다이렉션
}
Spring의 CommonsMultipartResolver를 사용하면 파일 업로드 시 메모리 버퍼 크기와 임계값을 설정할 수 있으므로 대용량 파일 업로드를 효과적으로 다룰 수 있습니다.
3. 파일업로드 컨트롤러 고도화 (조각화 포함)
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 업로드된 파일을 스트림으로 읽어와 조각적으로 처리
byte[] buffer = new byte[1024]; // 조각 크기 설정
int bytesRead;
try (InputStream inputStream = file.getInputStream();
OutputStream outputStream = new FileOutputStream("uploaded_" + file.getOriginalFilename())) {
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
return "File uploaded successfully!";
} catch (IOException e) {
e.printStackTrace();
return "File upload failed!";
}
}
}
4. 비동기 업로드 설정
- 업로드 성능 향상을 위해 비동기 업로드 설정을 하는 것이 필요하다. Spring에서 비동기 업로드 처리를 하려면 @Async, @EnableAsync 어노테이션을 사용한다.
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class FileUploadService {
@Async
public CompletableFuture<String> uploadFileAsync(MultipartFile file) {
try {
// 비동기로 파일 업로드 처리
// ...
return CompletableFuture.completedFuture("File uploaded asynchronously!");
} catch (Exception e) {
e.printStackTrace();
return CompletableFuture.completedFuture("File upload failed asynchronously!");
}
}
}
5. 비동기 업로드 컨트롤러
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.concurrent.CompletableFuture;
@RestController
public class AsyncFileUploadController {
private final FileUploadService fileUploadService;
@Autowired
public AsyncFileUploadController(FileUploadService fileUploadService) {
this.fileUploadService = fileUploadService;
}
@PostMapping("/async-upload")
public CompletableFuture<String> asyncUploadFile(@RequestParam("file") MultipartFile file) {
return fileUploadService.uploadFileAsync(file);
}
}
-새벽코딩-
'생각정리' 카테고리의 다른 글
[Shell] war 배포 및 서버 재기동 sh (2) | 2024.07.24 |
---|---|
[배치 명령어] 데몬서버 배치 실행시 사용 명령어 (0) | 2023.05.15 |
[LIS] 최장 증가 부분 수열(Longest Increasing Subsequence) (0) | 2023.05.15 |
[Eclipse] 이클립스 세팅시 마주한 에러들 (0) | 2023.04.05 |
[github] github을 사용하는 2가지 방법 (0) | 2023.03.29 |