본문 바로가기
교재 실습/자바 웹 개발 워크북

68. DB 커넥션풀 (2)

by Jint 2022. 7. 13.

2. DB 커넥션풀 만들기

web05 프로젝트의 spms.util 패키지를 생성하여 DBConnectionPool 클래스를 생성한다(그림 1).

 

그림 1 (DBConnectionPool 클래스의 파일 경로)

package spms.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;

public class DBConnectionPool {
	String url;
	String username;
	String password;
	ArrayList<Connection> connList = new ArrayList<Connection>(); //Connection 객체 보관할 ArrayList
	
	//DB커넥션 생성에 필요한 값 준비
	public DBConnectionPool(String driver, String url, String username, String password) throws Exception {
		this.url = url;
		this.username = username;
		this.password = password;
		
		Class.forName(driver);
	}
	
	//DB 커넥션 객체 가져오기
	public Connection getConnection() throws Exception {
		if(connList.size() > 0) {//유효성 체크
			//Connection conn = connList.remove(0);
			Connection conn = connList.get(0);
			if(conn.isValid(10)) {
				return conn;
			}
		}
		return DriverManager.getConnection(url, username, password);
	}

	//DB 커넥션 객체 connList에 반환(반납)
	public void returnConnection(Connection conn) throws Exception {
		connList.add(conn);
	}

	//웹 애플리케이션 종료 전 데이터베이스와 연결된 것 끊기
	public void closeAll() {
		for(Connection conn : connList) {
			try{conn.close();} catch (Exception e) {}
		}
	}
}

 

- ArrayList<Connection> 인스턴스 변수

Connection 객체를 보관할 ArrayList를 준비한다.

ArrayList<Connection> connList = new ArrayList<Connection>(); //Connection 객체 보관할 ArrayList

생성자에서는 DB 커넥션 생성에 필요한 값을 매개변수로 받는다.

//DB커넥션 생성에 필요한 값 준비
public DBConnectionPool(String driver, String url, String username, String password) throws Exception {
    ...
}

 

- getConnection() 메서드

DB 커넥션을 달라고 요청받으면, ArrayList에 들어 있는 것을 꺼내 준다. DB 커넥션 객체도 일정 시간이 지나면 서버와의 연결이 끊어지기 때문에, 유효성 체크를 한 다음에 반환한다.

Connection conn = connList.get(0);
if(conn.isValid(10)) {
    return conn;
}

ArrayList에 보관된 객체가 없다면, DriverManager를 통해 새로 만들어 반환한다.

return DriverManager.getConnection(url, username, password);

 

- returnConnection() 메서드

커넥션 객체를 쓰고 난 다음에는 이 메서드를 호출하여 커넥션 풀에 반환한다. 그래야만 다음에 다시 사용할 수 있다.

//DB 커넥션 객체 connList에 반환(반납)
public void returnConnection(Connection conn) throws Exception {
    connList.add(conn);
}

 

- closeAll() 메서드

웹 애플리케이션을 종료하기 전에 이 메서드를 호출하여 데이터베이스와 연결된 것을 모두 끊어야 한다.

for(Connection conn : connList) {
    try{conn.close();} catch (Exception e) {}
}

물론 웹 애플리케이션이 종료할 때 데이터베이스와 연결된 것을 끊지 않아도, 일정 시간이 지나면 서버에서 자동으로 끊는다. 하지만, 데이터베이스는 여러 웹 애플리케이션에서 공동으로 사용하는 자원이기 때문에, 사용하지 않을 때는 바로바로 자원을 해제시키는 것이 바람직하다. 특히 365일, 24시간 내내 구동되고, 접속자가 많은 그런 서버인 경우는 약간의 자원 낭비가 시스템에 엄청난 영향을 끼칠 수 있다. 프로그래밍할 때 이런 세세한 부분을 신경써야 한다.

 

참고도서 : https://freelec.co.kr/book/1674/

 

[열혈강의] 자바 웹 개발 워크북

[열혈강의] 자바 웹 개발 워크북

freelec.co.kr

댓글