본문 바로가기

프로그래밍/JSP

JDBC - 커넥션 풀

커넥션  




데이터베이스와 연결된 커넥션을 미리 만들어서 (pool)속에 저장

필요할 때에 커넥션을 풀에서 가져다 쓰고 다시 풀에 반환하는 기법 


JDBC API 이용한 커넥션  사용 순서

1. 필요 라이브러리

 1) Commons-DBCP 

 2) Commons-Pool

http://www.apache.org/index.html#projects-list 에서 필요한 라이브러리 다운가능









커넥션 풀 초기화 예제

DBCPInits.java

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package jdbcs;
 
import java.sql.DriverManager;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
 
import org.apache.commons.dbcp2.ConnectionFactory;
import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
import org.apache.commons.dbcp2.PoolableConnection;
import org.apache.commons.dbcp2.PoolableConnectionFactory;
import org.apache.commons.dbcp2.PoolingDriver;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
 
public class DBCPInits extends HttpServlet {
 
    @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        loadJDBCDriver();
        initConnectionPool();
    }
    // 데이터베이스의 드라이버 로드
        private void loadJDBCDriver() {
             try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                System.out.println("드라이버 로드 성공!");
            } catch (ClassNotFoundException ex) {
                // TODO: handle exception
                throw new RuntimeException("Fail to load JDBC Driver",ex);
            }
        }
    // POOL 드라이버 로드, 설정, 풀등록
    private void initConnectionPool() {
        try {
            
            String jdbcUrl = "jdbc:oracle:thin:localhost:1521:orcl";
            String username = "userinfo"//데이터베이스명
            String pw = "1234"//비밀번호
            
            //커넥션풀이 새로운 커넥션을 생성할 때 사용할 커넥션팩토리를 생성.
            ConnectionFactory connFactory = new DriverManagerConnectionFactory(jdbcUrl, username, pw);
            // PoolableConnection을 생성하는 팩토리 생성.
            // DBCP는 커넥션을 보관할 때 PoolableConnection 을 사용
            // 실제 커넥션을 담고 있있으며, 커넥션 풀을 관리하는데 필요한 기능을 제공한다.
            // 커넥션을 close하면 종료하지 않고 커넥션 풀에 반환
            PoolableConnectionFactory poolableConnFactory = new PoolableConnectionFactory(connFactory, null);
            
            //커넥션이 유효한지 여부를 검사할 때 사용하는 쿼리를 지정한다.
            poolableConnFactory.setValidationQuery("select 1");
            
            //커넥션 풀의 설정 정보를 생성한다.
            GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
            
            //유휴 커넥션 검사 주기
            poolConfig.setTimeBetweenEvictionRunsMillis(1000L * 60L * 5L);
            //풀에 보관중인 커넥션이 유효한지 검사할지 유무 설정
            poolConfig.setTestWhileIdle(true);
            //커넥션 최소 개수
            poolConfig.setMinIdle(4);
            //커넥션 최대 개수
            poolConfig.setMaxTotal(50);
            //커넥션 풀을 생성. 생성자는 PoolabeConnectionFactory와 GenericObjectPoolConfig를 사용
            GenericObjectPool<PoolableConnection> connectionPool =
            new GenericObjectPool<>(poolableConnFactory, poolConfig);
            //PoolabeConnectionFactory에도 커넥션 풀을 연결
            poolableConnFactory.setPool(connectionPool);
            //커넥션 풀을 제공하는 jdbc 드라이버를 등록.
            Class.forName("org.apache.commons.dbcp2.PoolingDriver");
            PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
            //위에서 커넥션 풀 드라이버에 생성한 커넥션 풀을 등록한다. 이름은 pooltest 이다.
            driver.registerPool("pooltest", connectionPool);
            System.out.println("pooltest 이름으로 컨넥션 풀 등록 성공");
            
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
}
 
 
cs

1) 실제 커넥션을 생성할 ConnectionFactory를 생성한다. 

2) 커넥션 풀로 사용할 PoolableConnection을 생성하는 PoolableConnectionFactory를 생성한다. 

3) 커넥션 풀 설정 정보를 생성한다. 

4) 커넥션 풀을 사용할 JDBC 드라이버를 등록한다.


web.xml

1
2
3
4
5
  <servlet>
     <servlet-name>DBCPInits</servlet-name>
    <servlet-class>jdbcs.DBCPInits</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
cs

- web.xml에 커넥션 풀 등록해야 사용 가능