最近写的数据查询系统,前台html+miniUI,后台java,数据库Oracle,查询数据很慢,230行的数据,每页显示20条记录,点击下一页load很慢,chrome显示searchData的函数执行需要8s左右。经测试,searchData主要的时间开销在open connection上,一般open函数需要6000左右ms(偶尔几十ms,不知道为什么)。由于是server端分页,所以,每load一页,就open DB connection,然后执行,再close。考虑能不能每次open后不关闭,这样能提高查询效率。网上搜了下,有个数据库连接池的东西。具体用法如下:
1. ojdbc6.jar,放tomcat的lib下面。
2. web-inf的web.xml增加如下内容:
<resource-ref>
<description>dbconnection</description>
<res-ref-name>jdbccsrdb1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
于是web.xml变成:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<description>dbconnection</description>
<res-ref-name>jdbccsrdb1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
3. Tomcat的conf下的context.xml增加
<Resource name="jdbccsrdb1" auth="Containner" type="javax.sql.DataSource" factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
maxActive="20"
maxIdle="1"
maxWait="100"
username="hirflapp"
password="hirfl910"
driverClassName = "oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@XX.XX.XX.XX:1521:csrdb1"/>
4. 自己写一个数据库连接池的类:
import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;
import javax.sql.DataSource;
public class DBPool {private static DataSource pool;
static{
Context env = null;
try{
InitialContext ctx = new InitialContext();
pool = (DataSource)ctx.lookup("java:comp/env/jdbccsrdb1");
if(pool==null)
System.err.print("jdbccsrdb1 is unknown database");
}catch(Exception e)
{
System.err.print("error");
}
}
public static DataSource getPool()
{
return pool;
}
}
5. 在自己的数据库连接类中使用上面的pool:
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import oracle.sql.CLOB;
public class DataBase {
public static Connection getConnection() {
Connection conn = null;
try {
conn = DBPool.getPool().getConnection(); //使用pool
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
protected void open(String sql) throws Exception{
if(connection == null) {
connection = getConnection();
}
stmt = connection.prepareStatement(sql);
}
protected void close() throws Exception{
if(connection != null && connection.getAutoCommit()) {
connection.close();
connection = null;
}
}
}
经测试,第一次加载时,open connection 需要7s或者8s的时间,然后每点击下一页都不存在connetion的时间了,速度一下子提高了。
另外,搜搜看到一些说法,连接池貌似不需要关闭。待研究。