框架内核 使用线程池技术 和线程单例技术
package utils;
import java.sql.Connection;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
public class DBUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
private static BasicDataSource ds;//连接池
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();///实现线程单例 本质上是map 一个Thread 对应一个value(Connection)
static {
try {
Properties props = new Properties();
// 获得配置文件中的信息 反射机制
props.load(DBUtils.class.getClassLoader().getResourceAsStream(
"utils/db.properties"));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
ds = new BasicDataSource();//创建线程池对象
ds.setDriverClassName(driver);//给线程池做配置
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(password);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws Exception {
// Connection con = ds.getConnection();
Connection con = tl.get();///取得当前线程的连接
if (con == null) {/// 如果线程池里没有该链接
con = ds.getConnection(); ///从连接池里获得连接
tl.set(con);//放入连接池中
}
return con;
}
public static void closeConnection() throws Exception{
Connection con = tl.get();
if (con != null) {
con.close();//放回到连接池中 而并不是将连接关闭
tl.set(null);/// 取消当前线程绑定的连接
}
}
public static void main(String[] args) throws Exception {
Connection con = getConnection();
System.out.println(con.getClass().getName());
}
}