Java如何编写一个util用于适配所有的连接池呢?

书欣 Java经验 发布时间:2022-10-07 21:41:36 阅读数:13375 1
下文笔者编写了一个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);
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202210/16651501614583.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者