import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.gw.entity.Wxbridgetoken;
public class DBPoolConnection {
private static DBPoolConnection dbPoolConnection = null;
private static DruidDataSource druidDataSource = null;
/**
* 数据库连接池单例
* @return
*/
public static synchronized DBPoolConnection getInstance(String url ,String username, String password){
Properties properties = loadPropertiesFile("/db_server.properties");
properties.setProperty("url", url);
properties.setProperty("username", username);
properties.setProperty("password", password);
try {
druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
dbPoolConnection = new DBPoolConnection();
return dbPoolConnection;
}
/**
* 返回druid数据库连接
* @return
* @throws SQLException
*/
public static DruidPooledConnection getConnection(Wxbridgetoken bean) throws SQLException{
DBPoolConnection dbp = new DBPoolConnection();
Map<String, Object> dbMap = Application.getDBMap();
dbp = (DBPoolConnection) dbMap.get(bean.getAPPID());
if(dbp == null ){
dbp = DBPoolConnection.getInstance(bean.getDBUrl(), bean.getUser(), bean.getPassword());
dbMap.put(bean.getAPPID(), dbp);
}
return dbp.druidDataSource.getConnection();
}
/**
* @param string 配置文件名
* @return Properties对象
*/
private static Properties loadPropertiesFile(String fullFile) {
Properties props = new Properties();
try(InputStream ins = ReadConfig.class.getResourceAsStream(fullFile)) {
props.load(ins);
return props;
} catch (IOException ex) {
// ex.printStackTrace();
return null;
}
}
}
-----------------------------------------------------------------------------------------------------------------------------
package com.gw.wx.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 通过读取sysConfig.properties中的配置信息
*
*/
public class ReadConfig {
private static String value;
private static String configFilePath = "/db_server.properties";
/**
* 根据key读取value
* @param key
* @return
*/
public static String getInfo(String key) {
Properties props = new Properties();
try(InputStream ins = ReadConfig.class.getResourceAsStream(configFilePath);) {
props.load(ins);
if (props.containsKey(key)) {
value = props.getProperty(key).trim();
} else {
return "";
}
} catch (IOException ex) {
// ex.printStackTrace();
return "";
}
return value;
}
}