public class DBManager {
private static final String PREFIX="jdbc:apache:commons:dbcp:";
private static Log log =LogFactory.getLog(DBManager.class);
private static Map<String,Mongo> mongoMap; //已经初始化的mongoDB的map信息
//已经初始化的mongoDB中 db名称信息 key:mongodb.id value:mongodb.dbname
private static Map<String,String> mongoDbMap;
private static Set<String> dbNames; //已经初始化数据库服务器标识
private static DBManager instance;
//线程变量保存连接
protected static ThreadLocal<Connection> threadConnection=new ThreadLocal<Connection>();
/**
* 返回DBManager实例
* @return
* @throws Exception
*/
public static DBManager getInstance() throws Exception{
if(instance==null){
instance=new DBManager();
}
return instance;
}
private DBManager() throws Exception{
initDB();
}
/**
* 返回所有初始化的数据库服务器标识
* @return 服务器标识数组
*/
public String[] getDBNames(){
String[] dbs=(String[]) dbNames.toArray();
String[] clones=Arrays.copyOf(dbs, dbs.length);
return clones;
}
/**
* 获取数据库连接
* @param dbKey 数据库连接池标识
* @return 数据库连接
* @throws SQLException
*/
public Connection getConnection(String dbKey) throws SQLException{
Connection conn=threadConnection.get();
if(conn==null||conn.isClosed()){
//如果连接不存在建立连接放入线程变量中
conn=DriverManager.getConnection(PREFIX+dbKey);
threadConnection.set(conn);
}
return conn;
}
/**
* 获取数据库连接
* @param dbKey 数据库连接池标识
* @param autoCommit 是否自动提交 true是 false否
* @return 数据库连接
* @throws SQLException
*/
public Connection getConnection(String dbKey,boolean autoCommit) throws SQLException{
Connection conn=getConnection(dbKey);
conn.setAutoCommit(autoCommit);
return conn;
}
/**
* 初始化数据库连接池
* @throws Exception 初始化失败
*/
public void initDB() throws Exception{
mongoMap=new HashMap<String,Mongo>();
mongoDbMap=new HashMap<String,String>();
dbNames=new HashSet<String>();
setupPool();
setupMongoDB();
}
/**
* 初始化数据库连接池
* 关系型数据库 使用DBCP建立
* @throws IOException
* @throws FileNotFoundException
*/
private void setupPool() throws Exception{
String filePath=this.getClass().getClassLoader().getResource("").getFile();
File f=new File(filePath+"conf/db");
File[] files=f.listFiles(new FilenameFilter(){
//过滤关系型数据库的配置文件
public boolean accept(File dir, String name) {
return name.matches("^db\\w*fu\\w*.properties$"); //是关系型数据库的配置文件
}
});
for(int i=0;i<files.length;i++){
log.debug("db configure file path"+(i+1)+":"+files[i].getAbsolutePath());
Properties p=new Properties();
p.load(new FileInputStream(files[i]));
String driverClassName=p.getProperty("jdbc.driverClassName");
String dbId=p.getProperty("jdbc.id");
if(driverClassName==null||dbId==null)
throw new Exception("db pool setup error!");
Class.forName(p.getProperty("jdbc.driverClassName")); //加载驱动类
//创建关系型数据库连接池
String connectURI=p.getProperty("jdbc.url");
//连接池相关设置
GenericObjectPool connectionPool=new GenericObjectPool(null,
Integer.parseInt(p.getProperty("dbcp.maxActive")),
GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION,
Long.parseLong(p.getProperty("dbcp.maxWait")),
Integer.parseInt(p.getProperty("dbcp.maxIdle")),
Integer.parseInt(p.getProperty("dbcp.minIdle")),
Boolean.parseBoolean(p.getProperty("dbcp.testOnBorrow")),
GenericObjectPool.DEFAULT_TEST_ON_RETURN,
Long.parseLong(p.getProperty("dbcp.timeBetweenEvictionRunsMillis")),
GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
Long.parseLong(p.getProperty("dbcp.minEvictableIdleTimeMillis")),
Boolean.parseBoolean(p.getProperty("dbcp.testWhileIdle"))
);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,p.getProperty("jdbc.username"),p.getProperty("jdbc.password"));
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
poolableConnectionFactory.setValidationQuery(p.getProperty("validationQuery"));
Class.forName("org.apache.commons.dbcp.PoolingDriver");
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(PREFIX);
driver.registerPool(dbId,connectionPool);
dbNames.add(dbId); //加入已经初始化的关系型数据库服务器标识中
}
}
/**
* 日志输出连接池状态
* 使用log info级别输出
* @param dbKey 数据库服务器标识
*/
public void showConnectionPoolStatus(String dbKey){
PoolingDriver driver;
try {
driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
ObjectPool connectionPool = driver.getConnectionPool(dbKey);
log.info("NumActive: "+connectionPool.getNumActive()+"| NumIdle: "+connectionPool.getNumIdle());
} catch (SQLException e) {
log.error("connection pool error:",e);
}
}
/**
* 非关系型使用mongoDB
* 简历mongoDB连接池
* @throws Exception
*/
private void setupMongoDB() throws Exception{
String filePath=this.getClass().getClassLoader().getResource("").getFile();
File f=new File(filePath+"conf/db");
File[] files=f.listFiles(new FilenameFilter(){
//过滤Mongodb的配置文件
public boolean accept(File dir, String name) {
return name.matches("^mongodb\\w*fu.properties$"); //是mongodb 的配置文件
}
});
for(int i=0;i<files.length;i++){
log.debug("mongodb configure file path"+(i+1)+":"+files[i].getAbsolutePath());
Properties p=new Properties();
p.load(new FileInputStream(files[i]));
String ip=p.getProperty("mongodb.ip");
String port=p.getProperty("mongodb.port");
String username=p.getProperty("mongodb.username");
String password=p.getProperty("mongodb.password");
String dbId=p.getProperty("mongodb.id");
String dbName=p.getProperty("mongodb.dbname");
Mongo mongo=new Mongo(ip,Integer.parseInt(port));
boolean auth=mongo.getDB(dbName).authenticate(username, password.toCharArray());
if(!auth){
throw new Exception("unauthorized");
}
else{
mongoMap.put(dbId, mongo);
mongoDbMap.put(dbId, dbName);
}
}
}
/**
* 获取mongoDb DB对象
* @param mongoId mongodb服务器的id标志
* @param dbName db名称
* @return DB对象
*/
public DB getMongoDB(String mongoId,String dbName){
Mongo mongdo=mongoMap.get(mongoId);
mongdo.setWriteConcern(WriteConcern.SAFE);
if(mongdo!=null)
return mongdo.getDB(dbName);
else
return null;
}
/**
* 获取mongoDb DB对象
* @param dbName db名称
* @return DB对象
*/
public DB getMongoDB(String dbName){
Mongo mongdo=mongoMap.get(SystemVar.DEFAULT_MONGO_DB_KEY);
mongdo.setWriteConcern(WriteConcern.SAFE);
if(mongdo!=null)
return mongdo.getDB(dbName);
else
return null;
}
/**
* 获取mongo db数据库默认数据库名称
* @param dbKey mongodb.id
* @return mongodb.dbname
*/
public String getMongoDefaultDbName(String dbKey){
return mongoDbMap.get(dbKey);
}
}
java配置多数据源多连接池的工具类,这里是mysql和mongoDB
最新推荐文章于 2024-07-30 00:19:15 发布