package com.ynxbd.common.config.db; import com.alibaba.druid.pool.DruidDataSource; import com.ynxbd.common.helper.ProperHelper; import com.ynxbd.common.helper.common.FileHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Properties; public class PacsDB { private final static Logger log = LoggerFactory.getLogger(PacsDB.class); private static DruidDataSource dataSource; static { dataSource = init(); } private static synchronized DruidDataSource init() { if (dataSource != null) { return dataSource; } final DruidDataSource dataSource = new DruidDataSource(); ProperHelper config = DataBase.getConfig(); dataSource.setDriverClassName(config.getString("pacs.driverClassName")); dataSource.setUrl(config.getString("pacs.jdbcUrl")); dataSource.setUsername(config.getString("pacs.username")); dataSource.setPassword(config.getString("pacs.password")); // 连接池配置 Integer min = config.getInteger("pacs.minIdle"); if (min != null) { dataSource.setMinIdle(min); } Integer max = config.getInteger("pacs.maxActive"); if (max != null) { dataSource.setMaxActive(max); } Integer initialSize = config.getInteger("pacs.initialSize"); if (initialSize != null) { dataSource.setInitialSize(initialSize); } dataSource.setMaxWait(60 * 1000); // 60s // 异步初始化连接 dataSource.setAsyncInit(true); dataSource.setValidationQuery("SELECT 1"); // 安全性 dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setTestOnReturn(false); // 打开PSCache,并且指定每个连接上PSCache的大小 dataSource.setPoolPreparedStatements(true); dataSource.setMaxPoolPreparedStatementPerConnectionSize(120); // 连接泄露检查 dataSource.setRemoveAbandonedTimeoutMillis(300000); // 关闭连接时输出错误日志,这样出现连接泄露时可以通过错误日志定位忘记关闭连接的位置 dataSource.setLogAbandoned(true); dataSource.setMinEvictableIdleTimeMillis(300000); // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 dataSource.setTimeBetweenConnectErrorMillis(60000); return dataSource; } /** * 获取连接 */ public static Connection getConnection() { Connection conn = null; try { if (dataSource == null) { dataSource = init(); } conn = dataSource.getConnection(); } catch (SQLException e) { log.error("Pacs数据库连接失败!{}, {}", dataSource.getUrl(), e.getMessage()); if (dataSource != null) { dataSource.close(); dataSource = null; } } return conn; } public static List select(String sql, Class clazz, DataBase.IPS ips) { return DataBase.select(getConnection(), sql, clazz, ips); } public static List select(String sql, Class clazz) { return DataBase.select(getConnection(), sql, clazz, null); } }