레이블이 WAS인 게시물을 표시합니다. 모든 게시물 표시
레이블이 WAS인 게시물을 표시합니다. 모든 게시물 표시

2010년 2월 4일 목요일

jeus auto reload Q/A 모음

수정된 서블릿 파일을 반영시키기 위해서는 위에서 처럼
(1) 해당 context에 AutoReload='true'로 세팅을 해두시던가,
(2) AutoReload='false'일 경우 webadmin이라는 console 툴을 이용해서
>reload    [ContextGroup] [Context] [Servlet] :  reload elements
하시면 됩니다.

그리고 현재 Context에 대한 세팅이 제대로 되어 있는지(AutoReload='true')를
체크하시기 위해서는 webadmin 으로 login하신 후
>cfg -c:컨텍스트명 명령을 해보시면 현재 Context의 세팅 상태를 알 수 있습니다

 

 

Jeus32\classes에는 유저가 개발한 소스를 두는 위치가 아님니다.
시스템 클래스만 두는 것입니다.
그 결과는 당연합니다.

E:\Jeus32\webhome\servlet_home\webapps\ping\WEB-INF\classes
에 두고 사용하시는것이 맞습니다.

만약 해당 클래스가 package성 프로그램이고
reload대상이 아니라면

$JEUS_HOME/lib/application에 두고 사용하시면 됩니다.

수고하세요.

 

 

님께서 현재 제우스 manager를 이용해서 셋팅을 하시는지 아니면
그냥 텍스트 모드로 하시는지 모르겠지만
간단하게 텍스트 모드 방법을 가르쳐 드리겠습니다.
그리고 기본적인 제우스 셋팅이라 보고 말씀 드리겠습니다.

Java Bean 파일을 자동으로 auto reload 하기 위해서는

※노드명은 콘솔창에서 hostname으로 확인할수 있습니다.
ex] c:\hostname

(tag를 넣으면 제대로 보이지 않기 때문에 .을 삽입 했습니다.)

1. java Bean Auto-reload
제우스 설치 폴더 -> config 폴더 -> 노드명폴더 -> 노드명_servlet_engine1 ->
jeus-web-dd_examples.xml 파일을 편집기(ultra edit, edit plus등)으로
열어 봅니다.
<.jeus-web-dd>
   <.context>
       <.context-name>Examples</context-name>
       <.docbase>examples</docbase>
       <.auto-reload>
           <.enable-reload>true</enable-reload>
           <.check-on-demand>true</check-on-demand>
       <./auto-reload>
   <./context>
<./jeus-web-dd>

위에 보시면 <.auto-reload> ~ <./auto-reload>를 그대로 복사 하셔서 넣어 주시면 됩니다.

 


>  > % http.m
>  > -------------
>  > *NODE
>  > hanuhm    
>  >              WEBTOBDIR="D:/Jeus40/webserver",
>  >            SHMKEY = 54000,
>  >            DOCROOT="D:/STLS/webapps",
>  >             PORT = "8080",
>  >
>  > % WEBMain.xml
>  > --------------
>  > < context >
>  >     < context-name >default< /context-name >
>  >     < context-path >/etls< /context-path >
>  > </context>
>  >
>  > % jeus-web-dd_default.xml
>  > ------------------------
>  > < jeus-web-dd >
>  >     < context >
>  >         < context-name >default< /context-name >
>  >         < docbase > < /docbase >
>  >         < auto-reload>
>  >             < enable-reload >true< /enable-reload >
>  >             < check-on-demand >true< /check-on-demand >
>  >          < /auto-reload >
>  >     < /context >
>  > < /jeus-web-dd >

 

BEANS는 컨텍스트 아래의 WEB-INF/classes 에 패키지 형태로 두거나

모든 컨텍스트에서 참조 가능하도록 JEUS_HOME/lib/application에 두는 것이

일반적입니다. OS 환경 CLASSPATH는 제우스에서 사용하지 않습니다.

다음과 같이 컨텍스트가 올바르게 등록되어있는지 확인해 보세요..

1) OS 환경설정 SERVLET_HOME 값 확인
2) WEBMain.xml의 <group-docbase> 값 확인
3) jeus-web-dd_컨텍스트명.xml의 <docbase> 값 확인

그러면 다음과 같이 컨텍스트의 절대경로를 얻을 수 있습니다.

4) SERVLET_HOME/group-docbase/docbase

결로적으로 jsp는 4)의 경로에 두고 사용하며 서블릿 혹은 빈즈는

5) SERVLET_HOME/group-docbase/docbase/WEB-INF/classes

에 두면 JSP에서 참조할 수 있습니다.

만약, 제우스가 4.2 버전 이상이라면 1) 설정은

JEUS_HOME/bin/jeus.properties에 등록되어 있습니다.

참고로, WEBMain.xml의 <servlet-home> 값이 설정되었다면

SERVLET_HOME 환경변수 값은 무시됩니다.. 즉, <servlet-home> 값이

우선 적용됩니다.


서블릿은 5) 경로에 두고 web.xml에 SerlvetRoot를 설정하면

"http://주소:포트/컨텍스트패스/servlets/서블릿명"

로 호출할 수 있습니다.

자세한 샘플과 설정은 매뉴얼을 참고하세요..

 

 


클래스페스가 설정된 곳에 실제로 그 클래스가 없는 것입니다.
참고로 jeus는 외부의 classpath를 쓰지 않습니다.
따라서 공통클래스의 경우 jeus_home/lib/application에 놓고 쓰고
추가 적인 classpath는 JEUSMain.xml에 user-classpath를 사용해서 추가 해서 사용 합니다.

 

 


> <EngineContainer>
>     <Name>container1</Name>
>     <CommandOption/>
>     <SequentialStart>false</SequentialStart>
>     
>      <UserClassPath>C:\home1\nafis\lib</UserClassPath>

 

 


JeusMain.xml에서 [UserClassPath] 태그를 사용하여 클래스패스를 명시해 준 경우에 이런 현상이 발생합니다.
현재 프로젝트에서 [UserClassPath] 태그를 반드시 사용해야 하는 상황이며,  사용하는 CONTEXT 에만 영향을 줘야하는 상황이어서  C:\Jeus33\lib\application 에 놓고 쓸수 있는 상황이 아닙니다.
CONTEXT 밑에 WEB-INF/LIB에 jar를 놓고 사용할 경우 servlet에서 안되는데. jsp에서는 인식을 하니... jsp로 바꾸어 해결했습니다.
문제는 프레임웍에서 제공하는 트랜젝션을 하나도 사용 못한다는거죠...

 

만약 그렇다면 UserClassPath를

추가하고자 하는 디렉토리에 마지막 부분에 \를 추가 해보시겠습니까..?

예를 들자면

c:\temp => c:\temp\

 

 

container.xml에서 해당 Context 엘리먼트의 속성으로 AutoReload="true"로 설정되어있습니다.

 

WebtoB / JEUS 간단 운영법

WebtoB / JEUS 간단 운영법
===================================================
WebtoB 설치 디렉토리 : /user2/handyr5/webtob
        환경설정파일 : /user2/handyr5/webtob/config/http.m
JEUS 설치 디렉토리   : /user2/handyr5/jeus
   JEUS 환경설정파일 : /user2/handyr5/jeus/config/incheon/JEUSMain.xml (엔진구성 설정)
                       /user2/handyr5/jeus/config/incheon/incheon_servlet_engineX/WEBMain.xml (서블릿 엔진 설정)
 

WebtoB 기동 : $ wsboot
WebtoB 종료 : $ wsdown  (wsdown -i)
* WebtoB는 80포트로 기동되므로 반드시 root로 기동/종료 하여야 한다(현재 8090포트).
 
JEUS 기동   : $ jboot
JEUS 종료   : $ jdown
* JEUS는 반드시 handyr5로 기동/종료 하여야 한다.
 
 
 
**** 모니터링 ****
 
WebtoB(Web Server)
-------------------------------------------
$ wsadmin
> ci -s         동시 접속자 수(browser)
Total Connected Clients = 357
 
> st -s         서비스 상태(수행속도, 요청횟수, 큐잉 등..)
 
 
 
JEUS(WAS)
-------------------------------------------
* jeusadmin
$ jeusadmin `hostname` -Uadministrator -Pjeusadmin
형식 : jeusadmin 호스트명 -U<계정> -P<암호>
 
handy1>pidlist              pid 조회
handy1_container1 : 13722
 
 
* webadmin
$ webadmin `hostname`_servlet_engine1 -U administrator -P jeusadmin
> st            엔진 상태
< memory information >
VM Total Memory    = 535691264 Bytes
VM Free Memory     = 460284912 Bytes
 

> ti            thread info
-- Thread State [MyGroup-hth1(112.100.10.2:19901)] --
[MyGroup-hth1(112.100.10.2:19901)-w0][waiting, wt=2482 ms]
[MyGroup-hth1(112.100.10.2:19901)-w1][active , rt=28322 ms, uri=/servlet/HIServlet]
[MyGroup-hth1(112.100.10.2:19901)-w2][waiting, wt=2128 ms]
....
    wt : waiting time(ms)
    rt : running time(ms)
    uri : 요청 url
 

로그
$WEBTOBDIR/log/ access log가 날짜별로 생성됨
$JEUS_HOME/logs/JeusServer/ JEUS system log가 날짜별로 생성됨. 날짜별 로그.log
               /엔진별로그/... / accesslog / JEUS servlet engine 의 accesslog(수행시간)
 

###### alias #####
alias jcfg 'cd $JEUS_HOME/config/`hostname`'                            JEUSMain.xml이 있는 위치로 이동
alias scfg 'cd $JEUS_HOME/config/`hostname`/`hostname`_servlet_engine1' WEBMain.xml이 있는 위치로 이동
alias scfg1 'cd $JEUS_HOME/config/`hostname`/`hostname`_servlet_engine1'
alias scfg2 'cd $JEUS_HOME/config/`hostname`/`hostname`_servlet_engine2'
alias wcfg 'cd $WEBTOBDIR/config'                                       http.m이 있는 위치로 이동
alias jlog 'cd $JEUS_HOME/logs/JeusServer'                              JEUS system log가 있는 위치로 이동
alias logs 'cd $JEUS_HOME/logs'                                         JEUS 의 로그 디렉토리로 이동
alias vlog 'tail -f $JEUS_HOME/logs/JeusServer/JeusServer_`date +%m%d%Y`.log'   tail -f JEUS_system_log
 
 
 
###### thread dump 뜨는 법 #####
ti 정보를 조회할 때 수행시간이 너무 오래 걸리는 것이 있거나
모든 thread가 full 되어서 서비스가 너무 느려지는 경우
현재 thread의 상태를 조회해서 thread가 어떤 상태인지 조회해 볼수 있다.
java process에 kill -3을 수행하면 해당 jvm 내의 모든 thread의 정보가
JEUS system log에 남겨진다.
위의 pid 조회 방법을 참고로 하여 java process의 pid를 조회한 후
 
$ kill -3 [java_pid]
 
를 수행하면 된다.
즉시 조회하고 싶으면 다른 telnet 창에서 vlog를 수행한 후
kill -3을 수행하면 된다.
 
운영중 문제가 발생하는 경우 thread dump와 로그는 아주 유용한 정보가 되므로
장애발생시 반드시 3~5초 간격으로 3번 정도 thread dump를 남겨서 
엔지니어에게 전달하도록 한다. 

 

JEUS초기설정시 변경 파일

 

JEUS 초기 설정시 설정파일 수정목록

 

1. JEUSMain.xml 수정

          - 경로 : {JEUS_HOME}/config/{HOSTNAME}/JEUSMamin.xml

 

2. WEBMain.xml 수정

          - 경로 : {JEUS_HOME}/config/{HOSTNAME}/{HOSTNAME}_servlet_engine1

                                                                                                           /JEUSMamin.xml

 

3. jeus-web-dd.xml 생성/수정

          - 경로 : {CONTEXT PATH}/WEB-INF/jeus-web-dd.xml

 

4. sample.m 수정

          - 경로 : {WEBTOBDIR}/config/sample.m 수정

          - 파일수정후 Compile필요 : wscfl -i sample.m

 

JEUS에서 jeusadmin명령

 

pidlist      : 활성화된 engines list 와 PID를 같이 보여줌.

nodelist   : 활성화된 node list를 보여줌.

 

boot        : boot Jeus Manager

down      : down Jeus Manager

 

deploy    : application 을 deploy한다

      -> deploy -n app_name

undeploy    : application 을 undeploy한다

      -> undeploy  app_name

 

   * undeploy 후 deploy시 WebToB(웹서버)의 와의 연결이 끊어진다.

   * 그러므로 위 명령은 불필요(웹서버의 연결이 없으면 사용가능)

 

Jeus JNDI 설정방법

JEUS DataSource & iBatis 를  사용하기 위해서는 총 3개의 설정파일 수정이 필요 합니다.
 
 1. web.xml 수정 
    
     web.xml 파일에 아래와 같은 부분을  추가 하셔야 합니다.
 
    <resource-ref>
        <res-ref-name>jdbc/DefaultDS</res-ref-name> 
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
 
 2. WEB-INF/jeus-web-dd.xml 파일  수정
   
    jeus-web-dd.xml 파일에 아래의 빨간색 부분을 추가해 주십시요.
    .......
        <res-ref>
            <jndi-info>
                <ref-name>jdbc/DefaultDS</ref-name>
                <export-name>jdbc/DefaultDS</export-name> ---> 제우스에 설정된 export-name
            </jndi-info>
         </res-ref>   
    </jeus-web-dd> 
 
3. sqlmap-config.xml 파일 수정
 
 iBatis 설정파일에 아래 내용을 정의해 주시면 됩니다.
    ......

    <transactionManager type="JDBC" >
        <dataSource type ="JNDI">
            <property name="DataSource" value="java:comp/env/jdbc/DefaultDS"/>---> 제우스에 설정된 export-name
        </dataSource>
    </transactionManager>

 

Tomcat JNDI 설정방법

  • Oracle 9i classes12.jar

JNDI Naming Resource 설정

1.       라이브러리들을 $CATALINA_HOME/common/lib 복사한다. 이외 디렉토리에 두면 안된다. ZIP 파일은 JAR 확장자를 바꿔야 한다. 톰캣은 JAR파일만 클래스패스에 추가한다.

2.       Connection 풀을 이용할 경우에는 ResultSet Connection 객체를 필히 직접 닫아 줘야만 한다.

3.       $CATALINA_HOME/conf/server.xml 혹은 컨텍스트별 XML 파일의 <Context> 자식 요소로 다음을 추가한다.

4.                <Resource name="jdbc/forumDb" auth="Container" type="javax.sql.DataSource"/>

5.                <!-- Resource name 속성을 이용해서 어플리케이션에서

6.                                javax.sql.DataSource 객체를 얻어가게 된다. -->

7.             

8.               

9.                <!-- 자세한 파라미터 설정은

10.               http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html 참조 -->

11.            <ResourceParams name="jdbc/forumDb">

12.              <parameter>

13.                <name>factory</name>

14.                <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>

15.              </parameter>

16.         

17.              <parameter>

18.                <name>maxActive</name>

19.                <value>100</value>

20.              </parameter>

21.         

22.              <parameter>

23.                <name>maxIdle</name>

24.                <value>30</value>

25.              </parameter>

26.         

27.              <parameter>

28.                <name>maxWait</name>

29.                <value>10000</value>

30.              </parameter>

31.         

32.                              <!-- DB 사용자명과 비밀번호 설정 -->

33.              <parameter>

34.               <name>username</name>

35.               <value>dbuser</value>

36.              </parameter>

37.              <parameter>

38.               <name>password</name>

39.               <value>dbpasswd</value>

40.              </parameter>

41.         

42.                              <!-- JDBC 드라이버 클래스 -->

43.              <parameter>

44.                 <name>driverClassName</name>

45.                 <value>oracle.jdbc.driver.OracleDriver</value>

46.              </parameter>

47.             

48.                              <!-- JDBC 접속 URL -->

49.              <parameter>

50.                <name>url</name>

51.                <value>jdbc:oracle:thin:@dbhost:1521:ORA</value>

52.              </parameter>

53.         

54.                  <!-- 커넥션에 문제 없는지 테스트하는 쿼리 -->

55.              <parameter>

56.                <name>validationQuery</name>

57.                <value>select sysdate</value>

58.              </parameter>

59.            </ResourceParams>

 

60.    어플리케이션의 web.xml파일에 다음을 추가하여 JNDI 리소스를 사용할 있도록 한다.

61.                              <resource-ref>

62.                                                   <description>Forum DB Connection</description>

63.                                                   <!-- 다음이 바로 리소스의 이름 -->

64.                                                   <res-ref-name>jdbc/forumDb</res-ref-name>

65.                                                   <res-type>javax.sql.DataSource</res-type>

66.                                                   <res-auth>Container</res-auth>

67.                              </resource-ref>

 

JSP/Servlet 에서 사용하기

이제 다음과 같이 JNDI 이용해 DataSource 객체를 얻고, 객체에서 커넥션을 얻어오면 된다.

 

다음은 서블릿을 작성하고, 서블릿에서 DB커넥션을 얻고, 쿼리를 날린 , 결과를 JSP 파일에 포워딩하여 JSTL 이용해 출력하는 것이다.

 

1.       예제 테이블과 데이터 SQL - 오라클 계정으로 다음과 같은 데이터를 생성했다고 가정하면

2.              create table test (

3.                                  num NUMBER NOT NULL,

4.                                  name VARCHAR2(16) NOT NULL

5.              );

6.             

7.              truncate table test;

8.             

9.              insert into test values(1,'영희');

10.          insert into test values(2, '철수');

11.          insert into test values(3, '미숙');

12.          commit;

 

13.    test.JndiDataSourceTestServlet 소스

14.          package test;

15.         

16.          import java.io.IOException;

17.          import java.sql.Connection;

18.          import java.sql.ResultSet;

19.          import java.sql.SQLException;

20.          import java.sql.Statement;

21.          import java.util.ArrayList;

22.          import java.util.HashMap;

23.          import java.util.List;

24.          import java.util.Map;

25.         

26.          import javax.naming.Context;

27.          import javax.naming.InitialContext;

28.          import javax.naming.NamingException;

29.          import javax.servlet.RequestDispatcher;

30.          import javax.servlet.ServletException;

31.          import javax.servlet.http.HttpServlet;

32.          import javax.servlet.http.HttpServletRequest;

33.          import javax.servlet.http.HttpServletResponse;

34.          import javax.sql.DataSource;

35.         

36.          public class JndiDataSourceTestServlet extends HttpServlet {

37.         

38.              protected void doGet(HttpServletRequest request,

39.                      HttpServletResponse response) throws ServletException, IOException {

40.         

41.                  Connection conn = null;

42.                  ResultSet rs = null;

43.                  Statement stmt = null;

44.         

45.                  try {

46.                      // 커넥션을 얻기 위한 전초작업. 부분을 메소드화 하면 되겠다. ------------

47.                      Context initContext = new InitialContext();

48.                      Context envContext = (Context)initContext.lookup("java:/comp/env");

49.                      DataSource ds = (DataSource)envContext.lookup("jdbc/forumDb");

50.                     

51.                      // 커넥션 얻기

52.                       conn = ds.getConnection();

53.                      //------------------------------------------------------------------

54.                     

55.                      String sql = "SELECT * from test";

56.                      stmt = conn.createStatement();

57.                     

58.                      rs = stmt.executeQuery(sql);

59.                     

60.                      List results = new ArrayList();

61.                     

62.                      while (rs.next()) {

63.                          Map row = new HashMap();

64.                         

65.                          row.put("num", rs.getString("num"));

66.                          row.put("name", rs.getString("name"));

67.                         

68.                          results.add(row);

69.                      }

70.                     

71.                      request.setAttribute("results", results);

72.                     

73.                      RequestDispatcher rd = request.getRequestDispatcher("/dbtest.jsp");

74.                      rd.forward(request, response);

75.                     

76.                  } catch (NamingException e) {

77.                      throw new ServletException("JNDI 부분 오류", e);

78.                  } catch (Exception e) {

79.                      throw new ServletException("뭔가 다른 부분 오류", e);

80.                  } finally {

81.                      // 리소스를 필히 반환할 !

82.                      if (rs != null) { try { rs.close(); } catch (Exception ignored) {} }

83.                      if (stmt != null) { try { stmt.close(); } catch (Exception ignored) {} }

84.                      if (conn != null) { try { conn.close(); } catch (Exception ignored) {} }

85.                  }

86.              }

87.          }

88.    web.xml 서블릿 등록

89.                              <servlet>

90.                                                   <servlet-name>dbtest.svl</servlet-name>

91.                                                   <servlet-class>test.JndiDataSourceTestServlet</servlet-class>

92.                              </servlet>

93.                              <servlet-mapping>

94.                                                   <servlet-name>dbtest.svl</servlet-name>

95.                                                   <url-pattern>/dbtest.svl</url-pattern>

96.                              </servlet-mapping>

97.    /dbtest.jsp 소스

98.          <%@ page contentType="text/html" pageEncoding="EUC-KR" %>

99.          <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

100.       <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

101.      

102.       <!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en">

103.       <html>

104.       <head>

105.       <title>JNDI DataSource Test</title>

106.       </head>

107.                        <body                  bgcolor="#FFFFFF">

108.                           <h2>Results</h2>

109.                          

110.                           <c:forEach var="row" items="${results}">

111.                                                                    NUM : ${row.num}<br />

112.                                                                    Name : ${row.name}<br />

113.                                                                    <hr />

114.                           </c:forEach>

115.       </body>

116.       </html>

 

117.이제 브라우저에서 "/dbtest.svl" 호출해보면 결과를 있다.

 

전역적인 JNDI 리소스 이용

<Resource> <ResourceParams> 요소를 server.xml <GlobalNamingResources> 자식노드로 옮기면 특정 어플리케이션이 아니라, 톰캣에 설치된 전체 어플리케이션에서 사용 있게 된다. 하지만 어플리케이션 "<Context>" 다음과 같은 설정을 해야 한다.

                    <ResourceLink

                                         name="jdbc/forumDb"

                                         global="jdbc/forumDb"

                                         type="javax.sql.DataSource"

                      />

 

아니면 server.xml에서 <Host> 요소의 자식으로 다음을 추가하면 컨텍스트별 설정 필요없이 전체 어플리케이션 컨텍스트에서 GlobalNamingResources 지정된 JNDI 리소스를 사용할 있다.

 

                    <DefaultContext>

                                         <ResourceLink

                                                             name="jdbc/forumDb"

                                                             global="jdbc/forumDb"

                                                             type="javax.sql.DataSource"

                                           />

        </DefaultContext>

 

문제가 생겼어요!

1.       DB 커넥션이 간혹 끊어져요.
Tomcat
작동중인 JVM 가비지 컬렉션을 , 시간이 JNDI Resource 파라미터로 설정한 maxWait보다 길게 경우 DB 커넥션이 끊어질 있다.
CATALINA_OPTS=-verbose:gc
옵션을 주면 $CATALINA_HOME/logs/catalina.out 가비지 컬렉션 상황이 기록된다. 거기에 GC 작업에 걸린 시간도 나오니 그것을 참조로 maxWait 파라미터를 늘려주면 된다. 보통 10~15초로 주면 된다.
GC
시간은 거의 99% 이상 1 이내에 끝나야 하나보다..

2.       무작위로 커넥션이 close 되요.
그건.. Connection 객체를 이상 close 했기 때문이다.
DB Connection Pool
close() 호출할 정말로 닫는 것이 아니라, 단지 재사용할 있다고 표시만 뿐이다.
커넥션을 사용하다가 close()하면 다른 쓰레드이서 커넥션을 있는데, 이걸 현재 쓰레드에서 계속 잡고 있다가 다시 close() 해버리면, 다른 쓰레드에서 사용중에 close()됐다고 나와 버리게 되는 거다.

3.                  conn.close();

4.                  conn = null;

위와 같이 커넥션을 close() 뒤에 바로 null 설정하여 절대로 다시 사용할 없게 만들면 이런 실수는 생기지 않을 것이다.

Tomcat 5.5 예제

        <Resource name="jdbc/myDbResource" auth="Container" type="javax.sql.DataSource"

               maxActive="10" maxIdle="5" maxWait="10000"

               username="ao" password="ao"

               driverClassName="com.mysql.jdbc.Driver"

               url="jdbc:mysql://localhost:3306/myWebApp"

 

               removeAbandoned="true"

               removeAbandonedTimeout="60"

               logAbandoned="true"

               validationQuery="select 1"

               testOnBorrow="true"

               testWhileIdle="true"

               timeBetweenEvictionRunsMillis="10000"

               minEvictableIdleTimeMillis="60000"

       />

 

저기서 removeAbandoned 리소스 반환에 실패한 (혹은 안한) 커넥션을 자동으로 닫아주는 것이다.

 

validationQuery 커넥션이 살아 있는지 테스트하는 코드이다.

 

MySQL, Connector/J Tomcat 5 예제

http://dev.mysql.com/doc/connector/j/en/cj-tomcat-config.html 나온 내용임.

<Context ....>

 

  ...

 

  <Resource name="jdbc/MySQLDB"

               auth="Container"

               type="javax.sql.DataSource"/>

 

  <!-- The name you used above, must match _exactly_ here!

 

       The connection pool will be bound into JNDI with the name

       "java:/comp/env/jdbc/MySQLDB"

  -->

 

  <ResourceParams name="jdbc/MySQLDB">

    <parameter>

      <name>factory</name>

      <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>

    </parameter>

 

    <!-- Don't set this any higher than max_connections on your

         MySQL server, usually this should be a 10 or a few 10's

         of connections, not hundreds or thousands -->

 

    <parameter>

      <name>maxActive</name>

      <value>10</value>

    </parameter>

 

        <!-- You don't want to many idle connections hanging around

         if you can avoid it, onl    y enough to soak up a spike in

         the load -->

 

    <parameter>

      <name>maxIdle</name>

      <value>5</value>

    </parameter>

 

    <!-- Don't use autoReconnect=true, it's going away eventually

         and it's a crutch for older connection pools that couldn't

         test connections. You need to decide if your application is

         supposed to deal with SQLExceptions (hint, it should), and

         how much of a performance penalty you're willing to pay

         to ensure 'freshness' of the connection -->

 

    <parameter>

      <name>validationQuery</name>

      <value>SELECT 1</value>

    </parameter>

 

   <!-- The most conservative approach is to test connections

        before they're given to your application. For most applications

        this is okay, the query used above is very small and takes

        no real server resources to process, other than the time used

        to traverse the network.

 

        If you have a high-load application you'll need to rely on

        something else. -->

 

    <parameter>

      <name>testOnBorrow</name>

      <value>true</value>

    </parameter>

 

   <!-- Otherwise, or in addition to testOnBorrow, you can test

        while connections are sitting idle -->

 

    <parameter>

      <name>testWhileIdle</name>

      <value>true</value>

    </parameter>

 

    <!-- You have to set this value, otherwise even though

         you've asked connections to be tested while idle,

         the idle evicter thread will never run -->

 

    <parameter>

      <name>timeBetweenEvictionRunsMillis</name>

      <value>10000</value>

    </parameter>

 

    <!-- Don't allow connections to hang out idle too long,

         never longer than what wait_timeout is set to on the

         server...A few minutes or even fraction of a minute

         is sometimes okay here, it depends on your application

         and how much spikey load it will see -->

 

    <parameter>

      <name>minEvictableIdleTimeMillis</name>

      <value>60000</value>

    </parameter>

 

    <!-- Username and password used when connecting to MySQL -->

 

    <parameter>

     <name>username</name>

     <value>someuser</value>

    </parameter>

 

    <parameter>

     <name>password</name>

     <value>somepass</value>

    </parameter>

 

    <!-- Class name for the Connector/J driver -->

 

    <parameter>

       <name>driverClassName</name>

       <value>com.mysql.jdbc.Driver</value>

    </parameter>

 

    <!-- The JDBC connection url for connecting to MySQL, notice

         that if you want to pass any other MySQL-specific parameters

         you should pass them here in the URL, setting them using the

         parameter tags above will have no effect, you will also

         need to use & to separate parameter values as the

         ampersand is a reserved character in XML -->

 

    <parameter>

      <name>url</name>

      <value>jdbc:mysql://localhost:3306/test</value>

    </parameter>

 

  </ResourceParams>

</Context>

 

Oracle 만을 위한 JNDI 설정

원문 : http://www.microdeveloper.com/html/JNDI_Orcl_Tomcat1p.html

 

1) Modify the server.xml file
In<CATALINA_HOME>/conf/server.xml between <GlobalNamingResources> and </GlobalNamingResources> add the following

   <Resource name="jdbc/<alias>"

   auth="Cont   ainer"

   type="oracle.jdbc.pool.OracleDataSource"

   driverClassName="oracle.jdbc.driver.OracleDriver"

   factory="oracle.jdbc.pool.OracleDataSourceFactory"

   url="jdbc:oracle:thin:@<host>:<port>:<sid>"

   [user=<user>]

   [password=<password>]

   maxActive="20"

   maxIdle="10"

   maxWait="-1" />

   

 

Example

<!-- Global JNDI resources -->

 <GlobalNamingResources>

 

 <!-- Test entry for demonstration purposes -->

 <Environment name="simpl   eVal   ue" type="java.lang.Integer" value="30"/>

 

 <!-- Editable user database that can also be used by

   UserDatabaseRealm to authenticate users -->

 <Resource name="UserDatabase" auth="Container"

   type="org.apache.catalina.UserDatabase"

   description="User database that can be updated and saved"

   factory="org.apache.catalina.users.MemoryUserDatabaseFactory"

   pathname="conf/tomcat-users.xml" />

    <!-- Every connection to 'db1' uses the same user -->

 <Resource name="jdbc/db1"

   auth="Container"

   type="oracle.jdbc.pool.OracleDataSource"

   driverClassName="oracle.jdbc.driver.OracleDriver"

   factory="oracle.jdbc.pool.OracleDataSourceFactory"

   url="jdbc:oracle:thin:@oracle.microdeveloper.com:1521:db1"

   user="scott"

   password="tiger"

   maxActive="20"

   maxIdle="10"

   maxWait="-1" />

    <!-- Every connection to 'db2' must provide a username and password -->  <Resource name="jdbc/db2"

   auth="Container"

   type="oracle.jdbc.pool.OracleDataSource"

   driverClassName="oracle.jdbc.driver.OracleDriver"

   factory="oracle.jdbc.pool.OracleDataSourceFactory"

   url="jdbc:oracle:thin:@oracle.microdeveloper.com:1521:db2"

   maxActive="20"

   maxIdle="10"

   maxWait="-1" />

</GlobalNamingResources>

 

2) Modify the context.xml file
In <CATALINA_HOME>/conf/context.xml between <Context> and </Context> add the following for each entry in the JNDI resource list:

<ResourceLink global="jdbc/<alias>" name="jdbc/<alias>" type="oracle.jdbc.pool.OracleDataSource"/>

 

Example

<!-- The contents of this file will be loaded for each web application -->

 <Context>

 

 <!-- Default set of monitored resources -->

 <WatchedResource>WEB-INF/web.xml</WatchedResource>

 <WatchedResource>META-INF/context.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->

 <!--

 <Manager pathname="" />

   -->

 <ResourceLink global="jdbc/db1" name="jdbc/db1" type="oracle.jdbc.pool.OracleDataSource"/>

 <ResourceLink global="jdbc/db2" name="jdbc/db2" type="oracle.jdbc.pool.OracleDataSource"/>

 </Context>

 

3) Modify the context's web.xml file (5.0.x step only - not necessary for 5.5.x)
In the <CONTEXT>/WEB-INF/web.xml between <web-app> and </web-app> add the following:

<resource-ref>

   <description><Your Description></description>

   <res-ref-name>jdbc/<alias></res-ref-name>

   <res-type>oracle.jdbc.pool.OracleDataSource</res-type>

   <res-auth>Container</res-auth>

</resource-ref>

 

Example

 

<resource-ref>

   <description>Oracle Development Datasource</description>

   <res-ref-name>jdbc/db1</res-ref-name>

   <res-type>oracle.jdbc.pool.OracleDataSource</res-type>

   <res-auth>Container</res-auth>

</resource-ref>

 

<resource-ref>

   <description>Oracle Development Datasource</description>

   <res-ref-name>jdbc/db2</res-ref-name>

   <res-type>oracle.jdbc.pool.OracleDataSource</res-type>

   <res-auth>Container</res-auth>

</resource-ref>

 

 

4) Restart Tomcat

 

 

 

 

 

 

1. DBCP 컴포넌트 설치

  1.1 http://commons.apache.org/downloads/index.html 에서 다음 컴포넌트 다운로드

    - Collections

    - DBCP

    - Pool

  1.2 각 컴포넌트의 jar 파일을 WEB-INF/lib로 import

  1.3 프로젝트 Properties의 Java Build Path에 WEB-INF/lib에 import한 jar를 추가

 

2. Tomcat 환경설정

 2.1 conf/Server.xml 파일에 다음 내용 추가

 <Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/>

 

  2.2. WEB-INF/web.xml 파일에 다음 내용 추가

 <resource-ref>
 <description>Oracle Datasource example</description>
 <res-ref-name>jdbc/myoracle</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

 

  2.3 conf/context.xml에 다음 내용 추가

 <ResourceLink global="jdbc/java62" name="jdbc/java62"
  type="oracle.jdbc.pool.OracleDataSource"/>

 

3. JSP, JAVA Source

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection(); // 새로운 연결을 요청하는 것이 아니고 풀로부터 연결 주소를 받도록 오버라이딩 되어 있음

...

conn.close(); // 실제로 연결을 닫는 것이 아니고 연결을 반환하도록 오버라이딩 되어 있음