日期:2014-05-16  浏览次数:20859 次

mysql的java连接池,用openSTA测试50人并发访问一万次,没有出现问题,很好用
package com.gosafari.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;

public class DataBaseConnection {

	private static int maxConnectNum = 20;

	private java.sql.Connection conn[] = new Connection[maxConnectNum];

	private static ArrayList<Connection> connectPool = new ArrayList<Connection>();

	private static int flag = 0;

	public DataBaseConnection() {
		if (flag == 0) {
			init();
		}
	}

	private Connection getConnectionFromDatabase() {
		Connection trueConn = null;
		try {
			// Class.forName("org.gjt.mm.mysql.Driver").newInstance();
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String url = "jdbc:mysql://localhost:3306/ssk?user=root&password=dzjc&useUnicode=true&characterEncoding=GBK";
			trueConn = DriverManager.getConnection(url);
		} catch (Exception ex) {
			System.out.println("数据连接出错了:" + ex.toString());
		}
		return trueConn;
	}

	// 这里建立所有的连接;
	private void init() {
		for (int i = 0; i < maxConnectNum; i++) {
			conn[i] = getConnectionFromDatabase();
			connectPool.add(i, conn[i]);
		}
		flag = 1;
	}

	// 从连接池中取得一个可用的连接
	public Connection getConnection() {
		Connection conn = null;
		if (connectPool.size() == 0) {
			try {
				java.lang.Thread.sleep(1000);
				getConnection();
			} catch (InterruptedException ex) {
				System.out.println("连接全部用光,这里sleep出错了.");
			}
		} else {
			conn = (Connection) connectPool.remove(0);
		}

		return conn;
	}

	// 提供给外部程序调用,不用的连接放回连接池当中...
	public boolean release(Connection conn) {
		return connectPool.add(conn);
	}

	public static void main(String[] args) {
	}
}

?