전공공부
Spring Batch를 이용한 대량의 insert 최적화 본문
계기
파일 시스템으로 관리되는 bin 파일을 WAS 서버로 불러와 사용하려 하였는데 Java OOM 이슈가 있어 DB에 해당 데이터를 적재한 후 필요한 만큼만 가져와 사용 할 필요가 있었다. 그래서 큰 용량의 데이터를 한 번에 insert 하게 되었는데 생각보다 시간이 너무 많이 걸려 이를 최적화 하기 위해서 사용해보았다.
구현
@Service
@RequiredArgsConstructor
public class ItemJdbcServiceImpl implements ItemJdbcService{
private final JdbcTemplate jdbcTemplate;
private int batchSize; // 배치 사이즈 크기 지정
public void saveAll(List<vo> items){
int batchCount = 0;
List<vo> subItems = new ArrayList<vo>();
for(int i = 0; i < items.size(); i++){
subItemns.add(items.get(i));
if((i+1)%batchSize == 0){
batchCount = batchInsert(batchSize, batchCount, subItems);
}
}
if(!subItems.isEmpty()){// 배치 사이즈 만큼 돌고 남은 나머지를 넣습니다.
batchCount = batchInsert(batchSize, batchCount, subItems);
}
}
public int batchInsert(int batchSize, int batchCount, List<vo> subItems){
jdbcTemplate.batchUpdate("INSERT INTO table (things,things1) VALUES (?,?)",
new BatchPreparedStatementSetter(){
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setInt(1,subItems.get(i).getThings());
ps.setInt(2,subItems.get(i).getThings1());
}
@Override
public int getBatchSize(){
return subItems.size();
}
});
subItems.clear();
batchCount++;
return batchCount;
}
}
before
insert into table (one) values one
insert into table (one) values two
insert into table (one) values three
after
insert into table (one) values
(one),
(two),
(three)
성능
건수 | 소요시간 | |
Mapper 방식의 insert | 100000 | 60s |
Spring Batch insert | 100000 | 10s |
'Study > Spring Boot' 카테고리의 다른 글
[Webflux] Webflux, MVC, Virtual Thread...? (0) | 2024.01.27 |
---|---|
[Spring] Hexagonal Arichtecture - MVC 패턴과 비교하다. (0) | 2024.01.21 |
Mockito를 사용한 단위 테스트에서 발생하는 다양한 이슈 (0) | 2024.01.20 |
[Spring] PSA(Portable Service Abstraction) + DI(Dependency Injection) (0) | 2024.01.19 |
[Hexagonal Architecture] 1장. 왜 헥사고날 아키텍쳐를 사용하는가? (0) | 2023.12.09 |