2007年11月11日 星期日

建立 DBCP ConnectionPool (不使用server.xml方式)


利用此方法也是另一種設定connection pool 的方法 , 不一樣的地方是, 這種方法設定相關的properties值是寫在程式, 若是要方便維護 , 就得用另一種方法, 有空再來寫吧。
詳細說明直接參考dbcp docs的說明就很清楚了。

package com.cps.sql;


import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.SharedPoolDataSource;

public class connectionManager
{
private static DataSource ds;

public static DriverAdapterCPDS cpds ;

public static SharedPoolDataSource tds;

private final static int maxActive = 100;

private final static int maxIdle = 10;

private final static int maxWait = 10;

private final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

private final static String url ="jdbc:sqlserver://test.infinitiessoft.com:1433";

private final static String username = "test";

private final static String password = "1234";

static
{

cpds = new DriverAdapterCPDS();
try {
cpds.setDriver(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();

}
cpds.setUrl(url);
cpds.setUser(username);
cpds.setPassword(password);

tds = new SharedPoolDataSource();
tds.setConnectionPoolDataSource(cpds);
tds.setMaxActive(maxActive);
tds.setMaxIdle(maxIdle);
tds.setMaxWait(maxWait);

ds = tds;

}

public static Connection getConnection() throws SQLException
{
Connection cn = null;
status();//印出連線狀態
//判斷連線的數量是否超過設定的數值
if(tds.getNumActive() < tds.getMaxActive()){
return ds.getConnection();
}else{
return cn;
}
}

public static void status(){
System.out.println("[NumActive]:"+tds.getNumActive());
System.out.println("[MaxActive]:"+tds.getMaxActive());
System.out.println("[MaxIdle]:"+tds.getMaxIdle());


}
public final static void freeConnection(Connection con){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public final static int getActiveCon(){
return tds.getMaxActive();
}

public final static int getIdle(){
return tds.getMaxIdle();
}

public final static int getNumActive(){
return tds.getNumActive();
}

public static void main(String[] a){

try {
Connection con1 = connectionManager.getConnection();
Connection con2 = connectionManager.getConnection();
for(int i = 0 ; i<100;i++){
connectionManager.getConnection();
}
connectionManager.freeConnection(con1);
connectionManager.freeConnection(con2);
Connection con3 = connectionManager.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}


}

沒有留言: