Connection Pool
Connection Pool의 대표기술와 DataSource에 대해 알아보자
DataSource란 DB와 Spring을 연결해주는 인터페이스이다. DataSource의 대표적인 구현체로는 DriverManagerDataSource, HikariDataSource이 있다.
Connection Pool은 말그대로 Connection을 미리 만들어놓고 재사용하는 것이다. 즉 세션 하나당 커넥션이 한개이므로 세션하나를 재사용한다.
반면에 DriverManagerDataSource는 커넥션을 매번 새로 만들어준다. 즉 세션이 새로 생긴다.
@Slf4jpublicclassMemberRepositoryV1{privatefinalDataSourcedataSource;publicMemberRepositoryV1(DataSourcedataSource){this.dataSource=dataSource;}publicMembersave(Membermember)throwsSQLException{Stringsql="insert into member(member_id, money) values(?, ?)";Connectioncon=null;PreparedStatementpstmt=null;try{con=getConnection();pstmt=con.prepareStatement(sql);pstmt.setString(1,member.getMemberId());pstmt.setInt(2,member.getMoney());pstmt.executeUpdate();returnmember;}catch(SQLExceptione){log.error("db error",e);throwe;}finally{close(con,pstmt,null);}}publicMemberfindById(StringmemberId)throwsSQLException{Stringsql="select * from member where member_id = ?";Connectioncon=null;PreparedStatementpstmt=null;ResultSetrs=null;try{con=getConnection();pstmt=con.prepareStatement(sql);pstmt.setString(1,memberId);rs=pstmt.executeQuery();if(rs.next()){Membermember=newMember();member.setMemberId(rs.getString("member_id"));member.setMoney(rs.getInt("money"));returnmember;}else{thrownewNoSuchElementException("member not found memberId="+memberId);}}catch(SQLExceptione){log.error("db error",e);throwe;}finally{close(con,pstmt,rs);}}publicvoidupdate(StringmemberId,intmoney)throwsSQLException{Stringsql="update member set money=? where member_id=?";Connectioncon=null;PreparedStatementpstmt=null;try{con=getConnection();pstmt=con.prepareStatement(sql);pstmt.setInt(1,money);pstmt.setString(2,memberId);intresultSize=pstmt.executeUpdate();log.info("resultSize={}",resultSize);}catch(SQLExceptione){log.error("db error",e);throwe;}finally{close(con,pstmt,null);}}publicvoiddelete(StringmemberId)throwsSQLException{Stringsql="delete from member where member_id=?";Connectioncon=null;PreparedStatementpstmt=null;try{con=getConnection();pstmt=con.prepareStatement(sql);pstmt.setString(1,memberId);pstmt.executeUpdate();}catch(SQLExceptione){log.error("db error",e);throwe;}finally{close(con,pstmt,null);}}privatevoidclose(Connectioncon,Statementstmt,ResultSetrs){JdbcUtils.closeResultSet(rs);JdbcUtils.closeStatement(stmt);JdbcUtils.closeConnection(con);}privateConnectiongetConnection()throwsSQLException{Connectioncon=dataSource.getConnection();log.info("get connection={}, class={}",con,con.getClass());returncon;}}
댓글 쓰기