java 数据库连接方式(四)

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import com.xxx.config.*;

/**
 * 连接池连接工厂实现类。<br>
 * 配置说明:<br>
 * DBMaxConnectionCount:连接池最大连接数<br>
 * DBMinConnectionCount:连接池最小连接数<br>
 * DBInitConnectionCount:连接池初始连接数<br>
 * DBUseCount:数据库连接对象使用次数,默认-1;<br>
 * DBTimeout:数据库连接对象空闲时间,默认-1;<br>
 * DBUseTime:数据库连接对象最大使用时间,默认-1;<br>
 * DBTimerInterval:数据库定时器整理连接池的间隔时间,默认-1;<br>
 * 如果DBTimerInterval配置为-1,则不启动连接池定时器。
 * @author 
 */
public class CPoolConnectionFactory extends SimpleConnectionFactory {
	int connectionPoolSize = 1;
	int connectionPoolMin = 1;
	int connectionPoolMax = 30;
	int connectionPoolFree = -1;
	int connectionUseCount = -1;
	long connectionWaitTimeout = -1;
	long connectionTimeout = -1;
	long connectionUseTime = -1;
	int timerInterval = -1;
	
	protected ArrayList connectionObjs;
	protected Timer timer; 
	
	protected CPoolConnectionFactory() {
	}
	
	/**
	 * 销毁连接池
	 */
	public void destroy() {
		synchronized (connectionObjs) {
			Iterator it = connectionObjs.iterator();
			while (it.hasNext()) {
				ConnectionObject co = (ConnectionObject) it.next();
				co.close();
			}
			this.connectionObjs.clear();
		}
	}

	/**
	 * 从连接池得到连接对象
	 * @return ConnectionObject对象
	 */
	public ConnectionObject getConnection() {
		ConnectionObject co = this.getConnectionInternal(false);
		return co; 
	}

	/**
	 * 新建连接对象
	 * @return 一个新的ConnectionObject对象
	 */
	public ConnectionObject newConnection() {
		ConnectionObject co = this.getConnectionInternal(true);
		return co; 
	}

	/**
	 * 释放连接对象到连接池
	 * @param co 将被释放的ConnectionObject对象
	 */
	public void freeConnection(ConnectionObject co) {
		if (co == null) return;
		synchronized (connectionObjs) {
			co.useCount++;
			if (connectionUseCount > 0 && co.useCount > connectionUseCount) {
				co.close();
				this.connectionObjs.remove(co);
				co = null;
			} else {
				co.endTransaction();
				co.closeStatement();
				co.isusing = false;
				co.lastAccess = System.currentTimeMillis();
			}
		}
	}

	/**
	 * 关闭连接对象
	 * @param co 将被关闭的ConnectionObject对象
	 */
	public void closeConnection(ConnectionObject co) {
		if (co == null) return;
		synchronized (connectionObjs) {
			co.close();
			this.connectionObjs.remove(co);
			co = null;
		}
	}

	/**
	 * 初始化
	 * @param conf 数据库配置
	 */
	public void init(Configs conf){
		super.init(conf);
		try {
			connectionPoolMin = Integer.parseInt(conf.getConfig(ConfigKeys.dbMinConnKey, "1"));
		}catch(Exception ex){}

		if (connectionPoolMin < 0)
			connectionPoolMin = 1;

		try {
			connectionPoolSize = Integer.parseInt(conf.getConfig(ConfigKeys.dbInitConnKey, "1"));
		}catch(Exception ex){}

		if (connectionPoolSize < connectionPoolMin)
			connectionPoolSize = connectionPoolMin;
		
		try {
			connectionPoolMax = Integer.parseInt(conf.getConfig(ConfigKeys.dbMaxConnKey, "30"));
		}catch(Exception ex){}

		if (connectionPoolMax < 0)
			connectionPoolMax = 100;
		
		if (connectionPoolMax < connectionPoolMin)
			connectionPoolMax = connectionPoolMin + 3;
		
		try {
			connectionUseCount = Integer.parseInt(conf.getConfig(ConfigKeys.dbUseCountKey, "-1"));
		}catch(Exception ex){}

		try {
			connectionTimeout = Long.parseLong(conf.getConfig(ConfigKeys.dbTimeoutKey, "-1")) * 60 * 1000;
		}catch(Exception ex){}

		try {
			connectionWaitTimeout = Long.parseLong(conf.getConfig(ConfigKeys.dbWaitTimeoutKey, "-1")) * 1000;
		}catch(Exception ex){}

		try {
			connectionUseTime = Long.parseLong(conf.getConfig(ConfigKeys.dbUseTimeKey, "-1")) * 60 * 1000;
		}catch(Exception ex){}
		
		try {
			timerInterval = Integer.parseInt(conf.getConfig(ConfigKeys.dbTimerIntervalKey, "-1")) * 60 * 1000;
		}catch(Exception ex){}
		
		if (timerInterval > 0) {
			timer = new Timer(); 
			timer.schedule(new TimerTask() { 
	            public void run() { 
	            	TimerEvent();
	            } 
	        }, timerInterval, timerInterval); 
		}
		
		connectionObjs = new ArrayList(connectionPoolMax);
		for (int i = 0; i < connectionPoolSize; i++) {
			ConnectionObject co = super.newConnection();
			this.connectionObjs.add(co);
		}
	}
	
	protected ConnectionObject getConnectionInternal(boolean isNew) {
		long sys = System.currentTimeMillis();
		while (true) {
			ConnectionObject ret = null;
			synchronized (connectionObjs) {
				if (connectionObjs.size() > 0 
					&& (isNew == false || this.connectionObjs.size() >= connectionPoolMax)) {
					ArrayList removes = new ArrayList();
					Iterator it = connectionObjs.iterator();
					while (it.hasNext()) {
						ConnectionObject co = (ConnectionObject) it.next();
						if (!co.isusing) {
							if (isNew) {
								co.close();
								this.connectionObjs.remove(co);
								break;
							}
							if ((connectionTimeout < 0 || System.currentTimeMillis() - co.createTime < connectionTimeout) && !co.isClosed()) {
								ret = co;
								break;
							}
							co.close();
							removes.add(co);
						}
					}
					if (removes.size() > 0) 
						this.connectionObjs.removeAll(removes);
				}
				
				if (ret == null && this.connectionObjs.size() < connectionPoolMax) {
					ret = super.newConnection();
					this.connectionObjs.add(ret);
				}
				//System.out.println("get connection ret=====================" + ret);
				if (ret != null) {
					ret.isusing = true;
					ret.lastAccess = System.currentTimeMillis();
					//System.out.println("get connection size=====================" + this.connectionObjs.size());
					return ret;
				}
			}
			if (this.connectionWaitTimeout > 0 && System.currentTimeMillis() - sys > this.connectionWaitTimeout)
				throw new DBException("已达到最大的等待时间,没取到可用的连接!");
			try {
				Thread.sleep(500);
			}catch(Exception ex){}
		}
	}

	protected void TimerEvent() {
		synchronized (connectionObjs) {
			if (connectionObjs.size() > 0) {
				ArrayList removes = new ArrayList();
				Iterator it = connectionObjs.iterator();
				int cc = 0;
				while (it.hasNext()) {
					ConnectionObject co = (ConnectionObject) it.next();
					try {
						if (!co.conn.isClosed()) {
							if (co.isusing) {
								if (connectionUseTime < 0 || System.currentTimeMillis() - co.lastAccess < connectionUseTime)
									continue;
							} else {
								if ((connectionTimeout < 0 || System.currentTimeMillis() - co.createTime < connectionTimeout)
									&& (connectionUseCount < 0 || co.useCount <= connectionUseCount)
									&& !co.isClosed()) {
									if (this.connectionPoolFree < 0 || cc < this.connectionPoolFree) {
										cc++;
										continue;
									}
								}
							}
						}
					}catch(Exception ex){
						ex.printStackTrace();
					}
					co.close();
					removes.add(co);
				}
				if (removes.size() > 0) 
					this.connectionObjs.removeAll(removes);
			}
			if (connectionObjs.size() < connectionPoolMin) {
				for (int i = this.connectionObjs.size(); i < connectionPoolMin; i++) {
					ConnectionObject co = super.newConnection();
					this.connectionObjs.add(co);
				}
			}
			//System.out.println("connection size***********************" + this.connectionObjs.size());
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值