日期:2014-05-19 浏览次数:20735 次
package com.rooyeetone.vhost.db; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.mongodb.Mongo; import com.mongodb.MongoException; import com.rooyeetone.vhost.utils.BlankUtil; /** * @author <a href="mailto:amoszhou@foxmail.com">周美华</a> * 功能描述:mongoDB数据库连接池 * @Since Jan 10, 2011 * */ public class DBConnectionPool { /** * mongoDB连接必须的参数 */ private String dbIp; private Integer dbPort; private Integer refreshTime; private static final Integer defaultRefreshTime = 60 * 60 * 1000; //默认刷新连接池 /** * 连接池的参数 */ private static List<Mongo> freeConnections = new ArrayList<Mongo>(); //空闲连接 private static Integer inUsed = 0; //已用连接数 private Integer minConnCount; //连接池中保持的最小连接数 private Integer maxConnCount; //连接池中保持的最大连接数 private static final Integer defaultConnCount = 3; //默认连接数 private Timer timer; /** * empty constructor */ public DBConnectionPool() { super(); } /** * constructor * @param dbIp * @param dbPort * @param dbName */ protected DBConnectionPool(String dbIp, Integer dbPort) { this(dbIp,dbPort,0,0,defaultRefreshTime); } /** * full option construtor * @param dbIp * @param dbPort * @param dbname * @param minConnCount * @param maxConnCount * @param dbUsername * @param dbPassword */ protected DBConnectionPool(String dbIp, Integer dbPort, Integer minConnCount, Integer maxConnCount,Integer refreshTime) { super(); this.dbIp = dbIp; this.dbPort = dbPort; this.minConnCount = (minConnCount == null ? defaultConnCount : minConnCount); this.maxConnCount = (maxConnCount == null ? 0 : maxConnCount); this.refreshTime = (refreshTime == null ? defaultRefreshTime : refreshTime); //每60分钟,自动刷新连接池中的连接 timer = new Timer(true); timer.schedule(new TimerTask(){ @Override public void run() { try { releaseAllConn(); createConnection(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }},this.refreshTime,this.refreshTime); } /** * * @author <a href="mailto:amoszhou@foxmail.com">周美华</a> * @Description free connection * @Since Jan 10, 2011 * @param mongo */ public void freeConnection(Mongo mongo){ if(null != mongo){ freeConnections.add(mongo); inUsed -- ; } System.out.println("[free Connection]-----> free size ====" + freeConnections.size() + " and in used =======" + inUsed); } /** * * @author <a href="mailto:amoszhou@foxmail.com">周美华</a> * 功能描述: 获取连接 * @Since Jan 10, 2011 * @return * @throws UnknownHostException * @throws MongoException */ public synchronized Mong