2007年10月2日 星期二

使用 dbcp 做 connection pool(下)

實做connectionManager

/**
* 2007-08-20 create by jimmy
*
*/
package com.infinitiessoft.sql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.*;
import javax.servlet.ServletException;
import javax.sql.*;
import org.apache.commons.dbcp.BasicDataSource;


/**
*
* @author jimmy
*/
public class ConnectionManager {

public static final String JDBC_MYSQL = "jdbc/mysql";
public static final String JDBC_ORCALE = "jdbc/orcale";
public String JDBC_TYPE;
public static DataSource dataSource = null;
public String connectionStatus = "";

public ConnectionManager(){
this.init();
}
public ConnectionManager(String type) {

if(type.equalsIgnoreCase(this.JDBC_ORCALE)){
this.JDBC_TYPE = this.JDBC_ORCALE;
}else{
this.init();
}
}

public void init(){
this.JDBC_TYPE = this.JDBC_MYSQL;
}

public Connection getConnection(){

Connection conn = null;
DataSource ds = null;
BasicDataSource bds = null;

try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup(JDBC_TYPE);

BasicDataSource dbs =(BasicDataSource)ds;
this.connectionStatus = "jdbc type:"+this.JDBC_TYPE+"MaxActive:"+dbs.getMaxActive()+",NumActive: " + dbs.getNumActive() + ",NumIdle: " + dbs.getNumIdle();
//System.out.println(this.connectionStatus);

if( dbs.getNumActive() >= dbs.getMaxActive()){
// System.out.println("`" + JDBC_TYPE + "' is an unknown DataSource");
// System.out.println("'Connection is Busy!!");
this.connectionStatus = "Connection is Busy!!";
}else{
conn = ds.getConnection();
}

}catch(Exception ex){
ex.printStackTrace();
}finally{
System.out.println(this.connectionStatus);
}
return conn;
}



public int getMaxActive(BasicDataSource bds){
return bds.getMaxActive();
}


public int getMaxIdle(BasicDataSource bds){
return bds.getMaxIdle();
}


public String printStatus(){
return this.connectionStatus;
}
public void freeConnection(Connection conn){

if(conn!=null){
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}



}

沒有留言: