可以使用ThreadLocal。将Connection对象存储到ThreadLocal中。
具体实现:
/**
*
*/
package cn.aura.web.login.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/**
* @author panghu
* @description 连接mysql工具类
* @date 2021年1月31日
*/
public class ConnUtils {
private static String driver = null;
private static String url = null;
private static String user = null;
private static String pwd = null;
private static Properties prop = new Properties();
// ThreadLocal:保证一个线程中只有一个连接
private static ThreadLocal<Connection> tl = new ThreadLocal<>();
static {
try {
prop.load(ConnUtils.class.getClassLoader().getResourceAsStream("db.properties"));
driver = prop.getProperty("jdbc.driver");
url = prop.getProperty("jdbc.url");
user = prop.getProperty("jdbc.username");
pwd = prop.getProperty("jdbc.password");
Class.forName(driver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConn() throws Exception {
// 先在ThreadLocal中获取
Connection conn = tl.get();
if(conn == null) {
conn = DriverManager.getConnection(url, user, pwd);
// 将conn对象存储到ThreadLocal中
tl.set(conn);
}
return conn;
}
public static void closeConn() throws Exception {
Connection conn = tl.get();
if(conn != null) {
conn.close();
// 一定要把null赋值给ThradLocal对象
tl.set(null);
}
}
}