Druid数据库连接池的简单使用

public class DruidPool {
	private static DruidDataSource _dds = null;
	private static class DruidPoolHolder {
		public static DruidPool _databasePool = new DruidPool();
	}
	static {
		NormalSettingFactory factory = NormalSettingFactory.getInstance();
		File file = new File("druidpool.properties");
		NormalSetting normalSetting = factory.createSetting(file,
				Setting.PROPERTY);
		Properties properties = normalSetting.getProperties();//读取配置文件
		try {
			_dds = (DruidDataSource) DruidDataSourceFactory
					.createDataSource(properties);
			System.out.println("DruidPool Inited");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private DruidPool() {}	//singleton
	public void init() {
		try {
			DruidPooledConnection connection = this.getConnection();
			connection.recycle();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 得到一个数据库连接池实例
	 * @return ConnectionPool 实例
	 */
	public static DruidPool getInstance() {
		return DruidPoolHolder._databasePool;
	}
	/**
	 * 得到一个连接
	 * @return DruidPooledConnection 一个连接
	 * @throws SQLException SQL异常
	 */
	public DruidPooledConnection getConnection() throws SQLException {
		return _dds.getConnection();
	}
	/**
	 * 关闭数据库连接池
	 */
	public void close() {
		_dds.close();
	}
}

    由于当中使用了我自己的SettingManager类,该类的地址在我的GitHub上,不过使用Java自带的Properties也可以实现配置.
    由于使用了LazyLoad,如果用户需要第一次就撞在完成,则可以考虑如下的调用顺序:

DruidPool druidPool = DruidPool.getInstance();
UUDIManager uudiManager = UUDIManager.getInstance();
MapperFactory mapperFactory = MapperFactory.getInstance();
Main_ServerSocket serverSocket = Main_ServerSocket.getInstance();
//----------------------------------------
//以上是声明组件
druidPool.init();
uudiManager.init();
mapperFactory.init();
serverSocket.init();
//----------------------------------------
//由于使用了LazyLoad,所以需要激活
mapperFactory.autoInit();

    接下来是配置文件的内容:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
username=root
password=delta-boyMIKE
filters=stat
initialSize=30
maxActive=5000
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=500

    恩,基本上就这么结束了.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.