커넥션 풀을 이용한 DB 접속
1. Servers 에서 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="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Resource
auth = "Container"
driverClassName = "oracle.jdbc.driver.OracleDriver"
url = "jdbc:oracle:thin:@localhost:1521:xe"
username = "scott"
password = "1234"
name = "jdbc/Oracle11g"
type = "javax.sql.DataSource"
maxActive ="50"
maxWait = "1000"
/>
</Context>
-----------------------------------------------------------------------------------------------------------------
MemberDAO 에서 커넥션 풀로 접속하는 방법(기존 파일 수정)
package jsp_practice;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class MemberDAO {
private DataSource ds;
public MemberDAO(){
try{
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Oracle11g");
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<MemberDTO> selectMember(){
ArrayList<MemberDTO> dals = new ArrayList<MemberDTO>();
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String sql="select * from member";
try{
//conn = DriverManager.getConnection(url,uid,upw);
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
String name = rs.getString("name");
String id = rs.getString("id");
String pw = rs.getString("pw");
String hp = rs.getString("hp");
String hp2 = rs.getString("hp2");
String hp3 = rs.getString("hp3");
String gender = rs.getString("gender");
MemberDTO mdto = new MemberDTO(name,id,pw,hp,hp2,hp3,gender);
dals.add(mdto);
}
}catch(Exception e){
e.printStackTrace();
}
return dals;
}
}
커넥션 풀(Connection Pool)
: 데이터베이스와 연결된 커넥션을 미리 만들어서 풀(pool) 속에 저장해 두고 있다가,
필요할 때에 커넥션을 가져다 쓰고 다시 풀에 반환하는 기능을 의미한다.
<사용 순서>
1. 풀에서 커넥션을 가져온다.
2. 커넥션을 사용한다.
3. 풀에 커넥션을 반납한다.
** 특징:
. 미리 만들어져 있기 때문에 커넥션을 생성하는 시간이 소비 되지않는다.
. 커넥션을 계속해서 재사용하기 때문에 생성되는 커넥션 수가 많지 않다.
--> 커넥션을 생성하고 닫는 시간을 줄일 수 있기 때문에 그 만큼 어플리케이션의
실행속도가 빨라지는 장점이 있다.
한번에 생성할 수 있는 커넥션의 수를 정할 수 있기 때문에 동시에 접속자 수가 몰려도
웹 어플리케이션이 쉽게 다운되지 않는 특징이 있다.
** 동시 접속자 처리 방법 :
커넥션 풀에서 생성되어 있는 커넥션의 갯수는 한정적이다. 동시에 접속자 수가 많아지면
남아있는 커넥션이 없기 때문에 클라이언트는 대기 상태로 전환된다. 커넥션이 반환이 되면
대기하고 있는 순서대로 커넥션이 제공된다.
** 커넥션 풀의 속성:
커넥션 풀은 여러 속성을 이용하여 설정할 수 있다.
maxActive : 커넥션 풀이 제공할 수 있는 커넥션의 갯수
whenExhaustedAction : 커넥션 풀에서 가져올 수 있는 커넥션이 없을 때 어떻게 동작할 지를 설정하는 속성
0일 경우 에러발생
1일 경우 maxWait속성에서 지정한 시간만큼 커넥션을 얻을 때까지 기다림
2일 경우 일시적으로 커넥션을 생성해서 사용
maxWait : whenExhaustedAction 속성의 값이 1일 때 사용되는 대기시간을 지정
단위 1/1000초, 0보다 작을 경우 무한대기
maxIdle: 사용되지 않고 풀에 저장될 수 있는 최대 커넥션의 갯수. 음수일 경우 제한이 없음
minIdle: 사용되지 않고 풀에 저장될 수 있는 최소 커넥션의 갯수.
testOnBorrow : true일 경우 커넥션 풀에서 커넥션을 가져올 때 커넥션의 유효성 여부를 검사
testOnReturn : true일 경우 커넥션 풀에 커넥션을 반환 할 때 커넥션이 유효한지의 여부를 검사
** 커넥션 풀을 사용하기 위한 톰캣 컨테이너 설정 방법 **
context.xml 파일에 다음과 같이 코드를 추가한다.
<Context>
<Resource
auth = "Container"
driverClassName = "oracle.jdbc.driver.OracleDriver"
url = "jdbc:oracle:thin:@localhost:1521:xe"
username = "scott"
password = "1234"
name = "jdbc/Oracle11g"
type = "javax.sql.DataSource"
maxActive ="50"
maxWait = "1000"
/>
</Context>
** java 프로그램에서 DB 접속하는 방법 크게 2가지로 분류
1. JDBC를 이용하는 방법 (ConnectionPoolBean을 이용)
2. WAS에서 제공하는 Connection Pool을 사용하는 방법
: JDBC 사용하는 방법
데이터베이스에서 제공하는 DB커넥션 클래스를 이용해서 DB에 접속하는 방법
사용자가 직접코드에 아이디와 비밀번호 IP등을 입력해서 커넥션 객체를 생성하고
그 커넥션을 이용해서 DB를 제어한다.
: WAS가 제공하는 Connection Pool을 사용하는 방법
사용자(개발자)가 코드에서 직접 DB에 연결하는 것이 아니라, 연결을
WAS(톰캣, 제우스, Weblogic)가 하고, 사용자는 WAS가 연결한
커넥션을 이용하는 방법
WAS가 스타트하면서 동시에 데이타베이스(오라클) 커넥션 객체를 미리생성하고
개발자는 그객체를 그냥 가져다 쓰는 것
DataSource를 이용하는 방법이 커넥션 풀 방법이다.
당연히 아이디와 비밀번호는 필요없다.(WAS가 알아서 접속한다.)
WAS가 만들어 놓은 커넥션은 각각 커넥션마다 이름이 있다.
Context 객체를 생성한다.
lookup메소드를 이용해서 매칭되는 커넥션을 찾는다
DataSource.getConnection()이용해서 커넥션을 확보한다.
'기존카테고리 > JSP' 카테고리의 다른 글
파일업로드 (0) | 2017.06.13 |
---|---|
[회원가입] 싱글톤 패턴 방식 - 회원입력, ID중복검사 (0) | 2017.06.08 |
리스트 출력 DTO,DAO,memberView.jsp (0) | 2017.06.07 |
회원정보 수정 및 로그아웃 (0) | 2017.06.07 |
로그인 입력, 처리페이지 (0) | 2017.06.07 |