Java如何编写一个util用于适配所有的连接池呢?
下文笔者编写了一个util类用于适配所有连接池,如下所示
实现思路:
使用jdbcTemplate.getDataSource()
获取DataSource
然后强制转换为指定的连接池对象
例:
package com.java265.util;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.enhydra.jdbc.pool.StandardPoolDataSource;
import org.enhydra.jdbc.standard.StandardConnectionPoolDataSource;
import org.logicalcobwebs.proxool.ProxoolDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBUtil {
public static String showDBInfo(JdbcTemplate jdbcTemplate){
try {
DataSource ds = jdbcTemplate.getDataSource();
String driver = "";
String connectInfo="";
String user="";
String password="";
if(ds instanceof StandardPoolDataSource){
StandardPoolDataSource sd = (StandardPoolDataSource)ds;
StandardConnectionPoolDataSource scd = (StandardConnectionPoolDataSource)sd.cpds;
driver = scd.getDriverName();
connectInfo = scd.getUrl();
user = sd.getUser();
password = sd.getPassword();
}else if(ds instanceof DruidDataSource){
DruidDataSource dds = (DruidDataSource)jdbcTemplate.getDataSource();
driver = dds.getDriverClassName();
connectInfo = dds.getUrl();
user = dds.getUsername();
password = dds.getPassword();
} else if(ds instanceof ProxoolDataSource){
ProxoolDataSource db = (ProxoolDataSource)jdbcTemplate.getDataSource();
password = db.getPassword();
user = db.getUser();
connectInfo = db.getDriverUrl();
} else if(ds instanceof ComboPooledDataSource){
ComboPooledDataSource db = (ComboPooledDataSource)jdbcTemplate.getDataSource();
driver = db.getDriverClass().toLowerCase();
connectInfo = db.getJdbcUrl();
user = db.getUser();
password =db.getPassword();
}
return " url:"+connectInfo+" user:"+user+" password:"+password;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
private static Logger log = Logger.getLogger(DBUtil.class);
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


