ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Servlet] 003. DBCP(DataBase Connection Pool) 개념 및 관찰
    SsY/Class 2023. 6. 7. 16:00
    728x90
    DBCP(DataBase Connection Pool) 개념
    ■■■ DBCP (Database Connection Pool) ■■■
    ○ 커넥션 풀(Connection Pool) 기법이란, 데이터베이스와 연결된 커넥션을
       미리 만들어 풀(Pool) 속에 저장해 두고 있다가 필요할 때 커넥션을
       풀에서 꺼내어 가져다 쓰고 사용이 끝나면 다시 풀에 반납(반환)하는 기법을 말한다.
    
    ○ 데이터베이스를 연결하기 위한 커넥션(Connection) 은 객체이다.
       이 객체는 새롭게 만들어지는(생성하는) 과정에서 많은 시스템 자원을 요구하게 된다.
       객체가 메모리에 할당되고, 객체에 사용할 여러 자원들에 대한 초기화 작업
       그리고 객체가 더이상 필요하지 않게 되었을 때 메모리를 회수하는 과정
       등에서 많은 비용이 발생하고 요구되는 것이다.
    
    ○ JSP 페이지를 생성할 때 마다 커넥션을 생성해서 사용하게 되면
       커넥션을 생성하고 닫는데 많은 시스템 자원을 요구하게 되기 때문에
       동시 접속자 수가 많은 웹 어플리케이션의 경우 전체 성능을 떨어뜨리는 원인이 될 수 있다.
       이러한 성능 저하 문제를 해결하기 위해 사용하는 일반적인 방식이
       커넥션 풀(Connection Pool) 기법인 것이다.
    ----------------------------------------------------------------------------------------------
    ○ DBCP 를 사용하기 위해서는 기본적으로 세 개의 패키지가 필요하다.
       - Jakarta-Commons DBCP 1.2.1 (commons-dbcp-1.2.1.jar)
       - Jakarta-Commons Collections 3.1 (commons-collections-3.1.jar)
       - Jakarta-Commons Pool 1.2 (commons-pool-1.2.jar)
    
       ※ 하지만, 톰캣 6.x 부터 톰캣 서버 내부에 기본적으로 탑재되어 제공되기 때문에
         (경로 : Tomcat Root\lib 또는 TomcatRoot\common\lib)
         (파일 : tomcat-dbcp.jar)
         다른파일을 추가하거나 변경하지 않아도 무방하다.
    ----------------------------------------------------------------------------------------------
    ○ 실습 환경 설정
    
     1. Eclipse > Project Explorer > Servers > Tomcat ... > context.xml
        파일 접근 및 열기
     2. 해당 파일의 맨 아래에 즉, 『</Context>』 닫히기 전에...
    	//--type의 DataSource는 이후 spring framework 에서 DataSource 를 관리할 때 사용
        //--@localhost 의 경우 오라클 설치되어있는 서버의 공인 ip 주소를 넣는다
        
         <Resource name="jdbc/myOracle" auth="Container"
                   type="javax.sql.DataSource"
                   driverClassName="oracle.jdbc.driver.OracleDriver"
                   url="jdbc:oracle:thin:@localhost:1521:xe"
                   username="사용자계정명" password="사용자패스워드"
                   maxActive="20" maxIdle="10" maxWait="-1">
         </Resource>
    
         내용을 추가한다.
    
         - name
          : 리소스 식별을 위한 이름
    
         - auth
          : 해당 리소스를 사용하게 되는 주체 
         - type
          : 리소스의 타입(패키지 경로 포함)
         - driverClassName
          : 사용할 JDBC Driver 의 클래스 이름
         - url 
          : JDBC Driver에 의해 연결할 Connection 에 대한 URL
         - username
          : connection 을 연결할 사용자 이름(오라클 사용자)
         - password
          : connection 을 연결할 사용자 이름에 대한 비밀번호(오라클 암호)
         - maxActive
          : connection Pool 에 제공할 최대 Connection 의 갯수
            (어플리케이션 최대 커넥션 사용량을 기준으로 지정.
             동시 접속자 수를 감안하여 지정.)
         - maxIdle	//-- idle : 쉬고 있는, 휴지 상태의
          : 사용되지 않고 풀(pool)에 저장될 수 있는 최대 Connection 의 갯수
         - maxWait
          : 대기 시간. 단위는 1/1000 초 //--(즉, 1000 을 입력하면 1초!)
            0 보다 작게 설정할 경우 무한히(응답을 받을 때 까지) 대기

    ex) 프린터기 - 인쇄 대기열(인쇄 풀)
    maxActive 와 maxIdle 은 동일하게 구성하는 것이 좋다. 
    위와 같이 따로 구성을 하게 되는 구조는 트래픽을 덜 발생하게 하기 위함이긴 하나
    현재는 동일하게 구성하는 것을 권장.
    기본 값은 8, 8 로 -> 0 8 -> 1 7 이렇게 사용된다


     DBCP 관찰
    - WebApp23
    • DBCPConn.java
    /*===================
    	DBCPConn.java
    ====================*/
    
    package com.util;
    
    import java.sql.Connection;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    
    public class DBCPConn
    {
    	//-- 싱글톤 패턴 디자인으로 구성
    	private static Connection conn = null;
    	
    	public static Connection getConnection()
    	{
    		if (conn == null)
    		{
    			try
    			{
    				//○ 컨텍스트 얻어내기
    				//-- 등록한 context 를 사용할 수 있도록 등록하는 과정
    				//-- javax.naming.Context 인지 확인!
    				Context ctx = new InitialContext();
    				//-- 컨텍스트(Context)를 얻어내는 가장 쉬운 방법은
    				//   『javax.naming.InitialContext()』클래스의
    				//   인스턴스를 생성하는 것이다.
    				//   → 『new InitialContext()』					
    				//   이렇게 얻어낸 컨텍스트(Context)를 활용하여		
    				//   이름과 객체를 바인딩하게 된다.
    				
    				//   ※ javax.naming.InitialContext 의 메소드
    				//      - bind(String str, Object obj)
    				//        : 서비스할 객체를 특정 이름으로 등록한다.
    				//      - rebind(String str, Object obj)
    				//        : 서비스할 객체를 특정 이름으로 다시 등록한다.
    				//      - list(String str)
    				//        : 특정 이름으로 서비스하는 객체 정보를 반환한다.
    				//      - unbinding(String str)
    				//        : 등록된 객체를 메모리에서 해제한다.
    				//      - Object lookup(String str)
    				//        : 서비스 중인 객체 정보를 얻어온다.
    
    				//-- 컨텍스트의 범위를 점점 좁혀나가는 구문
    				
    				// 『web.xml』로부터 환경설정을 얻어올 수 있도록 하겠다는 의미의 코딩
    				//-- 환경 설정에대한 부분은 context.xml 이 아닌 web.xml 을 통해 사용가능한지 서버 시작 시 확인하기 때문에
    				//-- Context evt = (Context)ctx.lookup("web.xml 로 부터 서비스중인 객체 정보를 얻어와");
    				//-- comp (컴포넌트) env(environment 환경) 
    				Context evt = (Context)ctx.lookup("java:/comp/env");
    				//-- 다른 형태로 변경 불가!!!!!!!!
    				
    				// 『web.xml』 내에서 『"jdbc/myOracle"』으로 등록된 객체 정보를 얻어오겠다는 의미
    				DataSource ds = (DataSource)evt.lookup("jdbc/myOracle");
    				
    				// DataSource 로 부터 Connection 을 얻어오겠다는 의미
    				conn = ds.getConnection();
    				
    			} 
    			catch (Exception e)
    			{
    				System.out.println(e.toString());
    			}
    		}
    		
    		return conn;
    	}// close getConnection()
    	
    	public static void close()
    	{
    		if (conn != null)
    		{
    			try
    			{
    				if (!conn.isClosed())
    				{
    					conn.close();
    				}
    			} catch (Exception e)
    			{
    				System.out.println(e.toString());
    			}
    		}
    		
    		conn = null;
    	}// close close()
    	
    }
    
    //--※ url 보다 조금 더 큰 개념 uri 
    //--※ 컨텐츠 보다 조금 더 크고 깊이 있는 개념 Context(컨텍스트)

    • web.xml
    <?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_3_1.xsd"
    	id="WebApp_ID" version="3.1">
    	<display-name>WebApp00</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>
    	
    <!-- 	
    	<servlet>
    		<servlet-name></servlet-name>
    		<servlet-class></servlet-class>
    	</servlet>
    
    	<servlet-mapping>
    		<servlet-name></servlet-name>
    		<url-pattern></url-pattern>	
    	</servlet-mapping>
    -->
    
    	<!-- DBCP -->
    	<resource-ref>
    		<description>Oracle DataSource</description>
    		<res-ref-name>jdbc/myOracle</res-ref-name>
    		<res-type>javax.sql.DataSource</res-type>
    		<res-auth>Container</res-auth>
    	</resource-ref>
    	
    </web-app>

    • context.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!--
      Licensed to the Apache Software Foundation (ASF) under one or more
      contributor license agreements.  See the NOTICE file distributed with
      this work for additional information regarding copyright ownership.
      The ASF licenses this file to You under the Apache License, Version 2.0
      (the "License"); you may not use this file except in compliance with
      the License.  You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    --><!-- The contents of this file will be loaded for each web application -->
    
    <Context>
    
        <!-- Default set of monitored resources. If one of these changes, the    -->
        <!-- web application will be reloaded.                                   -->
        <WatchedResource>WEB-INF/web.xml</WatchedResource>
        <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
    
        <!-- Uncomment this to disable session persistence across Tomcat restarts -->
        <!--
        <Manager pathname="" />
        -->
        
        <Resource name="jdbc/myOracle" auth="Container"
                  type="javax.sql.DataSource"
                  driverClassName="oracle.jdbc.driver.OracleDriver"
                  url="jdbc:oracle:thin:@localhost:xe"
                  username="scott" password="tiger"
                  maxActive="20" maxIdle="10" maxWait="-1">
        </Resource>
        
    </Context>

    • DBCPActionTest.jsp
    <%@page import="java.sql.Connection"%>
    <%@page import="com.util.DBCPConn"%>
    <%@ page contentType="text/html; charset=UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%
    	request.setCharacterEncoding("UTF-8");
    	String cp = request.getContextPath();
    %>
    <%
    	Connection conn = DBCPConn.getConnection();
    
    	String result = "";
    	
    	if(conn!=null)
    		result = "데이터베이스 연결 성공";
    	else
    		result = "데이터베이스 연결 실패";
    	
    	DBCPConn.close();
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>DBCPActionTest.jsp</title>
    <link rel="stylesheet" type="text/css" href="css/main.css">
    </head>
    <body>
    
    <div>
    	<h1>DBCP를 활용한 데이터베이스 접속 실습</h1>
    	<hr />
    </div>
    
    <div>
    	<!-- DB연결 테스트 결과 확인 -->
    	<h2><%=result %></h2>
    </div>
    
    </body>
    </html>
    728x90
Designed by planet-si