ConnectionManager 리팩토링 - 커넥션풀, JNDI
커넥션풀
커넥션풀에 커넥션 객체를 미리 생성하여 모아두고 재활용함으로써 비용과 시간을 줄인다.
InitialContext 클래스를 통해 정의한다.
https://all-record.tistory.com/104
JSP에서 DB연동 하기 - JNDI, DBCP(커넥션풀) 이용
EclipseJSPTomcat 8.0Oracle 11g JNDI외 DBCP란? ■ JNDI(Java Naming and Directory Interface) 란? JNDI의 정의를 보면 디렉터리 서비스에서 제공하는 데이터 및 객체를 발견하고 참고(lookup)하기 위한 자바 API라고 되어
all-record.tistory.com
JNDI란?
https://tomcat.apache.org/tomcat-9.0-doc/jndi-resources-howto.html
Apache Tomcat 9 (9.0.71) - JNDI Resources How-To
Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of ele
tomcat.apache.org
톰캣 가져오면서 만들어진 Servers의 context.xml에 Resource 태그를 통해 DB 정의
*server.xml : 톰캣 실행시 필요한 환경 설정을 해놓은 파일
*context.xml: 톰캣에서 구동되는 웹 애플리케이션의 설정을 해놓은 파일. 애플리케이션에서 사용할 수 있는 리소스의 이름 및 데이터 유형을 구성한다.
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>WEB-INF/tomcat-web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<Resource
name = "jdbc/mysql"
url = "jdbc:mysql://localhost:3306/DB이름"
driverClassName = "com.mysql.cj.jdbc.Driver"
username = "root"
password = "비밀번호"
auth = "javax.sql.Container"
type = "javax.sql.DataSource"
/>
</Context>
ConnectionManager 클래스의 getConnection() 메소드 리팩토링
public static Connection getConnection() {
Connection con = null;
Context ctx = null;
try {
ctx = new InitialContext();
Context env = (Context)ctx.lookup("java:comp/env");
DataSource ds = (DataSource)env.lookup("jdbc/mysql");
con = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
DataSource는 커넥션풀을 관리하는 객체를 생성하고,
getConnection() 메소드를 통해 커넥션 객체를 생성