(五)优化数据库连接

 

数据库在建立连接和释放连接都会消耗较大的cpu资源,为了性能,引入连接池的概念

 

public class DbUtil implements DataSource{


	
	private static DbUtil dbUtil = new DbUtil();
	
	public static DbUtil getInstance(){
		return dbUtil;
	} 
	
	private DbUtil(){
		
	}
	
	public static int POOL_MAX = 5;//最大连接数
	
	public Connection connection = null;//表示当前的connection
	
	private LinkedList<Connection> pool = new LinkedList<Connection>();//数据库连接池
	
	public Connection getConnection(){
		
		try {
			if(pool.size() == 0){
				Class.forName(dbDriver);
				for(int i=0; i< POOL_MAX;i++){
					pool.add(DriverManager.getConnection(dbUrl, dbUser, dbPassword));
				}
				System.out.println("初始化连接池,成功建立" + POOL_MAX + "个数据库连接放到连接池中!");
			}
			connection = pool.remove(0);//从连接池中取出一个并返回
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}
	
	/**
	 * 释放数据库链接到连接池中
	 */
	public void releaseConnection(){
		//放回到连接池中
		pool.add(connection);
		System.out.println("成功归还连接到连接池,当前连接池有" + pool.size() + "个空闲链接!");
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DbUtil dbUtil = new DbUtil();
		dbUtil.getConnection();
	}
	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean isWrapperFor(Class<?> arg0) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public <T> T unwrap(Class<T> arg0) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}

 这里使用了饿汉式单例模式,只允许创造一个dbutil对象

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值