커넥션 풀(Connection Pool)이란 데이터베이스와 연결된 커넥션을 미리 만들어서 풀(pool)속에 저장해 두고 있다가 필요할 때에 커넥션을 풀에서 가져다 쓰고 다시 풀에 반환하는 기법을 의미한다.

필자는 tomcat-dbcp 라이브러리에서 제공하는 dbcp 방식을 포스팅 해보겠다.

 

먼저 준비과정이 필요하다

DB에 연동하여 사용하는 것이므로 이클립스에서 프로젝트 안에 WEB-INF라는 디렉터리안에 lib디렉터리가 보일 것이다. 여기에 각자 사용하는 DB시스템의 jar파일을 복사해 넣어야 한다. 필자는 mariadb client용 2.7.2 버전을 사용하므로 아래와 같이 넣었다.

그리고 두개의 xml파일이 필요하다

첫번째는 프로젝트를 생성하면 자동으로 생성되어지는 web.xml파일이다. 이 파일은 한마디로 jsp파일을 실행하기전에 준비작업 즉, 초기화하는 용도로 주로 사용된다.(tomcat container가 해당 애플리케이션에서 가장 먼저 찾아 읽는 파일이 web.xml 이다.)

 

web.xml을 더블클릭하고 아래와 같이 입력하면된다. (태그 부분만 추가로 넣어주면 된다.)

(<display-name>태그에 어플리케이션 명(프로젝트 명)이 와야함)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>dbcp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
    <resource-ref>
         <description>Connection</description>
         <res-ref-name>jdbc/MariaDB</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
    </resource-ref>
  
</web-app>

*****************************************************************************************************************************

  <resource-ref> // 이 애플리케이션에서 참조하려는 자원이 무엇인가를 뜻하는 태그
         <description>Connection</description> //단순 설명란
         <res-ref-name>jdbc/MariaDB</res-ref-name> // 원하는 자원을 참조할 이름은(객체) jdbc/MariaDB
         <res-type>javax.sql.DataSource</res-type> // 자원의 타입은 javax.sql.DataSource
         <res-auth>Container</res-auth> // Container(tomcat container)에게 이 권한이 있다는 것 (tomcat Container에서 제공하는 dbcp 라이브러리를 사용하겠다는 의미)
    </resource-ref>

******************************************************************************************************************************

 

그리고 META-INF디렉터리에 또 하나의 xml파일을 만들어 넣어주어야 하는데 

META-INF에 마우스 올려놓고 우클릭 -> new -> other 로 들어가면 아래와 같은 창이 뜰 것이다

Next 누르고 파일명을 아래와 같이 설정하여 finish 누르면 

파일이 META-INF디렉터리에 생길것이다 그리고 아래와 같이 입력하여 저장하면 된다.

<Context>
  <Resource name="jdbc/MariaDB"
  auth="Container"
  type="javax.sql.DataSource"
  username="root"
  password="m1234"
  driverClassName="org.mariadb.jdbc.Driver"
  url="jdbc:mariadb://localhost:3306/test"
  maxActive="500"
  maxIdle="100"/>
</Context>

(url="jdbc:mariadb://localhost:3306/test" -> mariadb의 test db를 사용)

 

위와 같이 mariadb jar파일과 두개의 xml파일이 준비되었다면 커넥션 풀을 사용할 수 있다.

 

아래는 커넥션 풀을 사용하는 jsp코드 예시이다

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>

<%
	Connection conn = null;
	String sql = "select * from student order by num";

	try {
		Context init = new InitialContext();
		Context env = (Context) init.lookup("java:comp/env");
		DataSource ds = (DataSource) env.lookup("jdbc/MariaDB");
		conn = ds.getConnection();
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		while(rs.next()){
			out.println("<h3>" + rs.getInt(1) + ", "
					+ rs.getString(2) + "</h3>");
		}
		rs.close();
	} catch (Exception e) {
		out.println("<h3>데이터 가져오기 실패.</h3>");
		e.printStackTrace();
	}
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

위처럼 jsp파일이 수십개 된다고 생각해보자 그 수십개의 jsp파일이 모두 db와 연동하여 데이터를 처리해야한다면 그 때마다 db에 접속하는 반복적인 코드들이 모든 파일에 들어가야 할 것이다. 하지만 커넥션 풀을 사용하면 풀안에 담긴 커넥션들 중에 적당한 한개의 커넥션을 할당받아 사용하고 수행 완료하면 반환하는 과정을 거치기 때문에 관리하기 용이하다. 

 

반응형

+ Recent posts