ecsimsw

Connection pool / DBCP / JSP & mySql 커넥션 풀 본문

Connection pool / DBCP / JSP & mySql 커넥션 풀

JinHwan Kim 2020. 5. 19. 21:32

Connection pool

 

  이전에는 db에 엑세스하기 위해 매번 DB connection -> Handling -> DB close을 반복해야했다.

 

  필요한 db 접근이 많아질수록, 이런 과정은 부하를 낳을 것이다.

 

  Connection pool은 connection을 일정 개수 미리 만들어 두고, 웹서버가 db에 접근이 필요할 때마다 하나씩 빌리고 반납하는 방식으로 처리하여 위 문제를 해결한다. 

 

 

JSP과 mySql 연동, 커넥션 풀

 

1. 라이브러리 설치

 

  commons-collections / commons-pool / commons-dbcp 라이브러리를 필요로한다.

 

  appache commons에서 다운로드.

 

 

2. WebContent / WEB-INF / lib

 

  위에서 설치한 3개의 jar 파일 복사

 

 

 

3. Servers / context.xml 파일에 dbcp 설정

 

  <Context> </Context> 사이에 아래 Resource 정보를 기입한다.

 <Resource 
 	name="jdbc/_NAME_" ... 1
 	type="javax.sql.DataSource"  ...2
 	auth="Container"
 	maxActive="30" ... 3
 	maxIdle="3"       
 	maxWait="3000" ... 4 
 	username="_USERNAME_"  ... 5
 	password="_PASSWORD_"  
 	testOnBorrow="true"
 	driverClassName="com.mysql.jdbc.Driver"
 	url="jdbc:mysql://localhost:_PORT_/_DATABASE_NAME_> ... 6
</Resource>

  1) name은 자신이 정한다. 

 

  2) conntion을 만들어주는 객체 

 

  3) 미리 만들어둘 connection 개수 지정

 

  4) 사용 자원이 모두 소모됐을 때, 새로운 connection을 만들기까지 기다리는 시간

 

  5) mySql userName과 password

 

  6) mySql port와 database 이름. 

  

  tip. timeZone 오류가 난다면.

url="jdbc:mysql://localhost:_PORT_/_DATABASE_NAME_?serverTimezone=UTC">

 

 

4. 사용 방법

 

  1) 커넥션 풀 (DataSource 객체) 가져오기

Context init = new InitialContext();
DataSource dataSource = (DataSource) init.lookup("java:comp/env/jdbc/_NAME_");

  2) 커넥션 풀에서 conncetion 가져오기

Connection conn = dataSource.getConnection();

  3) 사용 후 자원 반납

if(conn != null) conn.close();

 

 

5. 사용 예시

public int insertMember(MemberDTO newMember) {
	Connection conn =null;
	PreparedStatement pstmt = null;
	String query = "insert into members values (?,?)";
	
	try {
		conn = dataSource.getConnection();
		
		pstmt = conn.prepareStatement(query);
		pstmt.setString(1, newMember.getId());
		pstmt.setString(2, newMember.getPw());
		
		pstmt.executeUpdate();
	}catch(Exception e){
		e.printStackTrace();
	}finally {
		try {
			if(conn != null) conn.close();
			if(pstmt != null) pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	return 0;
}
Comments