这个示例用到了ThreadLocal与dbcp,我觉得有点意思,就整理了下。使用dbcp,肯定要导入commons-dbcp.jar包。下面直接贴DBUtil代码:
public class DBUtil {
private static DataSource ds; //定义一个数据连接池
//threadLocal是线程的局部变量,它的实例通常是类中的 private static 字段
private static ThreadLocal<Connection> connLocal=new ThreadLocal<Connection>();
static{
Properties props=new Properties();
try {
props.load(DBUtil.class.getClassLoader().getResourceAsStream("dbcp.properties"));
ds=BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
Connection conn=connLocal.get();
if(conn==null){
conn=ds.getConnection();
connLocal.set(conn);
}
return conn;
}
public static void close() throws SQLException{
Connection conn=connLocal.get();
connLocal.set(null);//清空线程局部变量的内容
if(conn!=null){
try {
conn.close();
} catch (Exception e) {e.printStackTrace();}
}
}
}
下面是dbcp.properties配置内容:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/kyle1970
username=root
password=kyle1970
initialSize=2
maxActive=15
maxIdle=2
minIdle=1
maxWait=30000
个人感觉做了第二次的缓存。而ThreadLocal是每个线程都有的一个存储空间。