728x90
DB에 여러개의 정보를 빨리 insert를 해야하는데
for문 => parallerStream for문 => pool을 할당한 후 parallerStream for를 사용하여 insert를 시도해보았지만
속도는 향상되긴 하지만 생각만큼 빠르진 않아 검색을해보니 batch를 이용하여 insert를 하면 속도가 향상된다 하여 사용해보았다.
@Service
public class BatchConfig {
private PreparedStatement pstmt;
private Connection con;
// db url 주소 => jdbc:xxxx://ip:port/dbName
@Value("${db.pstmt.dbUrl}")
private String dbUrl;
// db user값
@Value("${db.pstmt.user}")
private String user;
// db 비밀번호
@Value("${db.pstmt.pwd}")
private String pwd;
public void pstmtBatch(List<TestModel> list) throws SQLException {
con = null;
pstmt = null;
String sql = "INSERT INTO MEMBER (NAME, PHONE_NUM) VALUES (?, ?)";
Properties props = new Properties();
props.put("user", user);
props.put("password", pwd);
try{
Class.forName("Altibase.jdbc.driver.AltibaseDriver");
con = DriverManager.getConnection(dbUrl, props);
pstmt = con.prepareStatement(sql);
for(int i = 0; i<list.size(); i++){
// name은 필수값
pstmt.setString(1, list.get(i).getName()); // 필수값
// phoneNum은 옵셔널이라 null일 경우 존재
if(!StringUtils.isEmpty(list.get(i).getPhoneNum())){
pstmt.setString(2, list.get(i).getPhoneNum());
}else{
pstmt.setObject(2, null, Types.NULL);
}
// 배치에 적재
pstmt.addBatch();
// 200건 마다 커밋 => 너무 많이 모아서 commit시 OOM 발생할 수 있다.
if((i % 200) == 0){
// 배치에 적재한 것들 실행 하여 DB에 커밋
pstmt.executeBatch();
pstmt.clearBatch();
con.commit();
pstmt.clearParameters();
}
}
// 200건이 안채워져도 커밋
con.commit();
}catch (Exception e){
con.rollback();
}finally {
// 메모리 누수방지를 위하여 항상 닫아준다.
if(pstmt != null) pstmt.close();
if(con != null) con.close();
}
}
}
놀랍게도 batch를 사용하니 이전 속도보다 대략적으로 20배정도 향상된 속도를 보여줬다 !!
728x90
'java' 카테고리의 다른 글
[java] spring boot에서 git hub 연동하기 (0) | 2021.12.19 |
---|---|
[java] 자바 스트림(Stream) 사용 및 예제 (0) | 2021.10.29 |
[java] Spring Tool Suite(STS) 설치하기 (0) | 2021.10.29 |
[java] 마이바티스 카멜케이스 자동으로 적용하는법 (0) | 2021.10.28 |
[java] 문자열을 DateTime 객체로 변환 (0) | 2021.10.27 |