您的位置:首页 > 其它

一个小应用的dbcp和c3p0配置实例

2013-07-12 14:28 387 查看
以下是一个小应用的数据库连接池配置,包括DBCP和C3P0的配制方法

因为是小应用,完全不涉及访问压力,所以配置上采取尽量节约数据库资源的方式

具体要求如下:
初始化连接数为0
连接不够,需要新创建时,每次创建1个
尽快回收空闲连接
需要开启prepareStatement缓存

具体用代码来说明

package com.yazuo.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Map;

/**
* Created by IntelliJ IDEA.
* User: Luo
* Date: 13-6-19
* Time: 下午3:33
*/
public class JdbcTemplateFactory {
static Logger log = LoggerFactory.getLogger(JdbcTemplateFactory.class);

private static JdbcTemplate jdbcTemplate;

/**
* 获取单例的jdbcTemplate,基于c3p0
*
* @return
*/
public static JdbcTemplate getJdbcTemplate() {
if (jdbcTemplate == null) {
synchronized (JdbcTemplateFactory.class) {
if (jdbcTemplate == null) {
try {
//读取配置文件
Map<String, String> jdbcProps = PropertiesUtil.getPropertiesMap("jdbc.properties");
//创建连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl(jdbcProps.get("jdbc.url"));
dataSource.setUser(jdbcProps.get("jdbc.username"));
dataSource.setPassword(jdbcProps.get("jdbc.password"));
//默认初始化连接为3,设置为0
dataSource.setInitialPoolSize(0);
//默认每次创建连接数为3,设置为1
dataSource.setAcquireIncrement(1);
//默认最小连接数是3,设置为0
dataSource.setMinPoolSize(0);
//默认最长空闲时间为0,即不会回收空闲连接,设置为10秒
dataSource.setMaxIdleTime(10);
//默认为不开启 prepareStatement 缓存,设置为最大缓存5个
dataSource.setMaxStatements(5);
jdbcTemplate = new JdbcTemplate(dataSource);
} catch (Exception e) {
throw new IllegalStateException("数据库连接创建失败", e);
}
}
}
}
return jdbcTemplate;
}

/**
* 获取单例的jdbcTemplate,基于dbcp
*
* @return
*/
public static JdbcTemplate getJdbcTemplateByDbcp() {
if (jdbcTemplate == null) {
synchronized (JdbcTemplateFactory.class) {
if (jdbcTemplate == null) {
try {
//读取配置文件
Map<String, String> jdbcProps = PropertiesUtil.getPropertiesMap("jdbc.properties");
//创建连接池
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(jdbcProps.get("jdbc.url"));
dataSource.setUsername(jdbcProps.get("jdbc.username"));
dataSource.setPassword(jdbcProps.get("jdbc.password"));
dataSource.setInitialSize(3);

//默认为不起动回收器,设置为30秒执行一次回收器
dataSource.setTimeBetweenEvictionRunsMillis(30 * 1000);
//默认为30分钟不使用的连接被认为空闲,设置为10秒钟
dataSource.setMinEvictableIdleTimeMillis(10 * 1000);
//开启 prepareStatement 缓存
dataSource.setPoolPreparedStatements(true);
jdbcTemplate = new JdbcTemplate(dataSource);
} catch (Exception e) {
throw new IllegalStateException("数据库连接创建失败", e);
}
}
}
}
return jdbcTemplate;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐