package utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.apache.log4j.Logger;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;
public class DBPoolConnection {
static Logger log = Logger.getLogger(DBPoolConnection.class);
private static DBPoolConnection dbPoolConnection = null;
private static DruidDataSource druidDataSource = new DruidDataSource();
static {
Properties properties = loadPropertiesFile("db_server.properties");
try {
druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); //DruidDataSrouce工厂模式
} catch (Exception e) {
log.error("获取配置失败");
}
}
/**
* 数据库连接池单例
*
* @return
*/
public static synchronized DBPoolConnection getInstance() {
if (null == dbPoolConnection) {
dbPoolConnection = new DBPoolConnection();
}
return dbPoolConnection;
}
/**
* 返回druid数据库连接
*
* @return
* @throws SQLException
*/
public DruidPooledConnection getConnection() throws SQLException {
return druidDataSource.getConnection();
}
/**
* @param fullFile 配置文件名
* @return Properties对象
*/
private static Properties loadPropertiesFile(String fullFile) {
String webRootPath = null;
if (null == fullFile || fullFile.equals("")) {
throw new IllegalArgumentException("Properties file path can not be null" + fullFile);
}
// webRootPath = DBPoolConnection.class.getClassLoader().getResource("").getPath();
// webRootPath = new File(webRootPath).getParent();
// webRootPath = new File(webRootPath).getParent();
InputStream inputStream = null;
Properties p = null;
// System.getProperty("user.dir")
try {
// inputStream = DBPoolConnection.class.getClassLoader().getResourceAsStream(fullFile);
// String filePath = System.getProperty("user.dir") + "/conf/"+fullFile;
// inputStream = new BufferedInputStream(new FileInputStream(filePath));
inputStream= ClassLoader.getSystemClassLoader().getResourceAsStream(fullFile);
ClassLoader.getSystemClassLoader().getResource(fullFile);
// inputStream = new FileInputStream(new File( System.getProperty("user.dir") + File.separator + fullFile));
p = new Properties();
p.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return p;
}
}
DbPoolConnection
最新推荐文章于 2021-02-24 10:10:00 发布