Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
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
Archives
Today
Total
관리 메뉴

전공공부

Spring Batch를 이용한 대량의 insert 최적화 본문

Study/Spring Boot

Spring Batch를 이용한 대량의 insert 최적화

monitor 2023. 1. 3. 15:02

계기


파일 시스템으로 관리되는 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