제 블로그는이 데이터베이스 연결 풀 정의가 잘 연결 풀을 쓸 수있는 능력 덕분에, 매우 간단하기 때문에, 물론, 데이터베이스 연결 풀을 사용자 정의하는 방법을 마쳤다. 그러나 우리는 오픈 소스 데이터베이스 연결 풀, 오픈 소스의 장점이 여기에 반영되어 사용할 수 있습니다, 걱정하지 마십시오.
자바 데이터베이스 연결 풀의 세 가지 오픈 소스 달성하기 위해 데이터의 독립적 인 소스를 제공합니다 있습니다 :
- DBCP 데이터베이스 연결 풀
- C3P0 데이터베이스 연결 풀
- 아파치 톰캣 내장 연결 풀 (아파치 DBCP)
1, DBCP 데이터베이스 연결 풀
DBCP 연결 풀은 아파치 소프트웨어 재단에서 오픈 소스, 응용 프로그램이 시스템에서 다음 두 jar 파일을 추가해야 DBCP 데이터 소스를 사용하여 구현입니다 :
- 평민 - dbcp.jar
- 평민 - pool.jar
오늘의 항아리 패키지 자원 I는 또한 네트워크 드라이브에 넣습니다. 링크 : HTTPS : //pan.baidu.com/s/1-Rj4TQLI_5DGLdfb45N62g
추출 코드 : ba3a는
이 열려있는 바이두 네트워크 디스크 전화 앱, 더 편리 오 조작의 내용을 복사
항아리 패키지 준비, 그래서 그것을 사용할 수 있습니다.
새로운 자바 프로젝트를 만듭니다.
그런 다음, 테스트 클래스 DBCPTest를 만들 테스트 코드를 작성
@Test
public void demo1(){
//首先使用BasicDataSource创建连接池
BasicDataSource basicDataSource = new BasicDataSource();
try {
//从连接池中获取连接
Connection connection = basicDataSource.getConnection();
String sql = "select * from account";
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet set = stmt.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
//释放资源
JDBCUtils.release(stmt, connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
이제 테이블 데이터를 확인하실 수 있습니다, 테스트 코드를 실행?
분명히, 심지어 데이터베이스가 매개 변수를 포기하지 않았다,이 테스트 코드는 분명 오류가있을 것입니다.
즉 지금, 매개 변수에 대한 설정 테스트 코드를 수정
@Test
public void demo1(){
//首先使用BasicDataSource创建连接池
BasicDataSource basicDataSource = new BasicDataSource();
//创建连接需要四个参数
basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicDataSource.setUrl("jdbc:mysql:///test");
basicDataSource.setUsername("root");
basicDataSource.setPassword("123456");
try {
//从连接池中获取连接
Connection connection = basicDataSource.getConnection();
String sql = "select * from account";
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet set = stmt.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
//释放资源
JDBCUtils.release(stmt, connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
이제 테스트 코드를 실행
성공적으로 테이블 데이터를 쿼리합니다. 그러나이 글을 쓰는이 한계를 가지고, 유연한 사용자의 요구를 수용하기 위해 데이터베이스 매개 변수 구성 파일에 기록해야한다.
src 디렉토리의 새로운 프로필 dbcp.properties
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql:///test
username = root
password =123456
쓰기 테스트 코드
@Test
public void demo2() throws Exception{
//读取dbcp.properties
Properties properties = new Properties();
properties.load(new FileInputStream(this.getClass().getResource("/dbcp.properties").getFile()));
DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
//从连接池中获取连接
Connection connection = dataSource.getConnection();
String sql = "select * from account";
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet set = stmt.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
//释放资源
JDBCUtils.release(stmt, connection);
}
다음 실행
을 성공적으로 실행합니다.
보다 포괄적 인 구성 파일을 첨부합니다.
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc
username=root
password=
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
2, C3P0 데이터베이스 연결 풀
: 항아리 패키지를 다운로드 https://sourceforge.net/projects/c3p0/
공식 웹 사이트 주소 : https://www.mchange.com/projects/c3p0/
공식 웹 사이트 다운로드 및 입구 및 튜토리얼 데이터베이스 연결 풀이 있었다.
문서는 공식 웹 사이트가 매우 상세한입니다 튜토리얼, 그래서이 있지만, 자세한 내용은.
직접 케이스.
쓰기 테스트 코드
@Test
public void demo1() throws Exception{
//创建一个连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//设置四个参数
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///test");
dataSource.setUser("root");
dataSource.setPassword("123456");
Connection connection = dataSource.getConnection();
String sql = "select * from account";
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet set = stmt.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
JDBCUtils.release(stmt, connection);
}
당신이 당신의 항아리 패키지 버전은 제 2 패키지, mchange - 평민 - 자바 0.2.3.4.jar를 추가 할 필요가 버전 이후 이후 c3p0-0.9.2, 버전임을 나타내는 시간 ClassNotFoundExecption 이상을 실행하는 경우, 그 주 .
이 다운로드 주소 항아리입니다. 링크 : HTTPS : //pan.baidu.com/s/17o0s92Us-UPQPJFeJjpOzQ
추출 코드 : lt2v는
이 열려있는 바이두 네트워크 디스크 전화 앱, 더 편리한 작업의 내용을 복사 오
유사하게, 구성 파일을 달성했다.
src 디렉토리 새 파일 C3P0-config.xml 파일에서
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///test</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="automaticTestTable">con_test</property>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
<user-overrides user="test-user">
<property name="maxPoolSize">10</property>
<property name="minPoolSize">1</property>
<property name="maxStatements">0</property>
</user-overrides>
</default-config>
<!-- This app is massive! -->
<named-config name="intergalactoApp">
<property name="acquireIncrement">50</property>
<property name="initialPoolSize">100</property>
<property name="minPoolSize">50</property>
<property name="maxPoolSize">1000</property>
<!-- intergalactoApp adopts a different approach to configuring statement
caching -->
<property name="maxStatements">0</property>
<property name="maxStatementsPerConnection">5</property>
<!-- he's important, but there's only one of him -->
<user-overrides user="master-of-the-universe">
<property name="acquireIncrement">1</property>
<property name="initialPoolSize">1</property>
<property name="minPoolSize">1</property>
<property name="maxPoolSize">5</property>
<property name="maxStatementsPerConnection">50</property>
</user-overrides>
</named-config>
</c3p0-config>
이것은 공식 문서 아래에서 직접 복사됩니다. 그런 다음 필요한 네 개의 데이터베이스 구성 매개 변수를 추가합니다.
그런 다음 테스트 코드를 작성
@Test
public void demo2() throws Exception{
//使用c3p0配置文件
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection connection = dataSource.getConnection();
String sql = "select * from account";
PreparedStatement stmt = connection.prepareStatement(sql);
ResultSet set = stmt.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
JDBCUtils.release(stmt, connection);
}
참고가 C3P0 데이터베이스 연결 풀 수동으로 구성 파일을로드 할 필요가 없습니다, C3P0 매우 인간적인,이 단계는 좋은 패키지되었습니다. 객체를 생성 한 후 직접 연결 얻을 ComboPooledDataSource의 getConnection () 메서드를 호출합니다. 구성 파일 이름은 C3P0-config.xml 파일이어야하며, 파일이 src 디렉토리 아래에 위치해야 함을 제공. 의미를 가지고 문서의 다른 구성 정보에 관해서는, 당신은 스스로 읽고 배울 수 있습니다.
이 기본 구성에서 구성 파일을 사용하여 매개 변수가없는 생성자를, 객체를 생성 호출하는 방법은 두 가지가 있습니다,하지만 당신은 생성자를 호출하는 경우, 구성 파일을 매개 변수가 ComboPooledDataSource
3, Tomcat은 연결 풀을 구축
알고 필요, 톰캣 연결 풀 콘텐츠 DBCP입니다.
우리는 세 가지 방법으로 Tomcat 웹 프로젝트에 배포 할 것이라는 점을 알고있다 :
- server.xml을 구성, 추가
꼬리표 - 별도의 XML 파일을 구성, 추가
꼬리표 - 직접 톰캣의 webapps 디렉토리에 웹 디렉토리를 복사
모든 프로젝트가 Tomcat을 실행할 수 있도록, 가상 디렉터리를 필요로한다. 가상 디렉터리은 무엇을 의미? 콘텍스트 요소를 지칭한다. 우리는 연결 풀링을 사용할 필요하면 다음과 같은 구성 컨텍스트를 만들 필요가
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<!-- maxActive: Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to -1 for no limit.
-->
<!-- maxIdle: Maximum number of idle dB connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this
and the minEvictableIdleTimeMillis configuration parameter.
-->
<!-- maxWait: Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<!-- username and password: MySQL dB username and password for dB connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is
org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
-->
<!-- url: The JDBC connection url for connecting to your MySQL dB.
-->
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
</Context>
그것은 공식 웹 사이트에서 내려 복사되었습니다.
그럼 여기서의 상황에 맞는 구성 요소?
콘텍스트 요소 3 개소 배치 :
- Tomcat 설치 디렉토리 /conf/context.xml (당신이 풀 구성 파일에 연결하는 경우, 그것은 것입니다 어떤 현재 프로젝트 모든 내부 톰캣 가상 호스트에 대한 유효)
- 톰캣 설치 디렉토리 / conf의 / 카탈 / 가상 호스트 디렉토리 /context.xml (당신이 풀 구성 파일에 연결하는 경우, 그것은 현재의 모든 가상 호스트에 작품이 유효합니다)
- 웹 프로젝트 /META-INF/context.xml의 루트 (당신이 풀 구성 파일에 연결하면 현재 프로젝트에만 유효합니다)
세 번째 구성에 대한 다음 프리젠 테이션
폴더 다음 WebRoot의 META-INF 파일은 새 파일의 context.xml을 만들
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true"
crossContext="true">
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000" username="root"
password="123456" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test" />
</Context>
의 context.xml 파일 쓰기가 완료된 후, Tomcat 서버를 시작, Tomcat은 자동으로 이동 파일을로드하고 Tomcat 컨테이너에있는 데이터베이스 연결 풀을 만듭니다. 이 시점에서 우리는 데이터베이스 연결 풀에 액세스하기 위해 JNDI 기술을 사용할 수 있습니다.
JNDI 어린이 신발이 기술을 이해하지 않는, 우리는 여기에 조금 말할 수 있습니다
JNDI는 (자바 명명 및 디렉토리 인터페이스) , 자바 하는 J2SE javax.naming 패키지에 해당하는 이름 지정 및 디렉토리 인터페이스,
주요 효과는 그이 API : 자바 객체 컨테이너 (컨테이너 지원 JNDI 톰캣)에 배치 할 수 있습니다 프로그램은 자바 객체를 취득 할 후 컨테이너 자바 객체의 이름은 단지를 통해 검색 할 이름을 지정합니다.
코어 API는 JNDI 컨테이너 객체 검색 방법 이름 조회 대응하는 용기를 나타내는 상황이다.
참고 :
Tomcat이 톰캣 디렉토리 폴더 아래, 데이터베이스와 연결 LIB mysql.jar에 파일을 복사하는 연결 풀, 데이터베이스 기반의 필요성을 만들 수 있습니다.
자바 프로그램은 JNDI를 통해 개체에 액세스하기 위해, 동일한 JNDI 컨테이너에서 실행해야합니다. 즉, 자바 프로그램은 너무 JNDI 프로그램 일반적으로 서블릿 또는 JSP를 사용하여, 톰캣 내에서 실행해야합니다.
을 보여줍니다.
새 프로젝트 파일에서 TomcatServlet 서블릿이다
/**
* 在该程序中,通过JNDI访问Tomcat内部的连接池
* @author Administrator
*
*/
public class TomcatServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//创建一个检索的对象
Context initCtx = new InitialContext();
//默认查找顶级的Java名称串 这是固定的:java:comp/env
Context envCtx = (Context) initCtx.lookup("java:comp/env");
//根据设置名称查找连接池对象
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
//获得连接池中的一个连接
Connection conn = ds.getConnection();
String sql = "select * from account";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet set = stmt.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
JDBCUtils.release(stmt, conn);
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
, 데이터베이스 기반 잊지 MySQL의 커넥터 - 자바 5.1.47- 복사하지 마십시오 bin.jar를을 파일 폴더의 톰캣 lib 디렉토리를 설치하려면, 다음의 MyEclipse 배포 프로젝트에서 실행됩니다. 그런 다음 브라우저에서 서블릿 프로그램을 방문
쿼리가 성공 지침을 제공합니다.