功能完善的Java串連池調用執行個體

來源:互聯網
上載者:User

標籤:statement   自動認可   except   llb   names   next   java   amp   enum   

/**
* Title: ConnectPool.java
* Description: 串連池管理器
* Copyright: Copyright © 2002/12/25
* Company:
* Author :
* Version 2.0
*/


import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
* 管理類DBConnectionManager支援對一個或多個由屬性檔案定義的資料庫連接
* 池的訪問.客戶程式可以調用getInstance()方法訪問本類的唯一執行個體.
*/
public class ConnectPool
{
static public ConnectPool instance; // 唯一執行個體
static public int clients;
public Vector drivers = new Vector(); //驅動
public PrintWriter log;
public Hashtable pools = new Hashtable(); //串連

/**
* 返回唯一執行個體.如果是第一次調用此方法,則建立執行個體
*
* @return DBConnectionManager 唯一執行個體
*/
static synchronized public ConnectPool getInstance()
{
if (instance == null)
{
instance = new ConnectPool();
}

clients++;

return instance;
}

/**
* 建構函數私人以防止其它對象建立本類執行個體
*/
public ConnectPool() {
init();
}

/**
* 將連線物件返回給由名字指定的串連池
*
* @param name 在屬性檔案中定義的串連池名字
* @param con 連線物件
*/
public void freeConnection(String name, Connection con)
{
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null)
{
pool.freeConnection(con);
}
else
{
System.out.println("pool ==null");
}
clients--;
}

/**
* 獲得一個可用的(閒置)串連.如果沒有可用串連,且已有串連數小於最大串連數
* 限制,則建立並返回新串連
*
* @param name 在屬性檔案中定義的串連池名字
* @return Connection 可用串連或null
*/
public Connection getConnection(String name)
{
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null)
{
//return pool.getConnection();
return pool.returnConnection();
}
return null;
}

/**
* 獲得一個可用串連.若沒有可用串連,且已有串連數小於最大串連數限制,
* 則建立並返回新串連.否則,在指定的時間內等待其它線程釋放串連.
*
* @param name 串連池名字
* @param time 以毫秒計的等待時間
* @return Connection 可用串連或null
*/
public Connection getConnection(String name, long time)
{
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null)
{
return pool.getConnection(time);
}
return null;
}

/**
* 關閉所有串連,撤銷驅動程式的註冊
*/
public synchronized void release()
{
// 等待直到最後一個客戶程式調用
if (--clients != 0)
{
return;
}

Enumeration allPools = pools.elements();
while (allPools.hasMoreElements())
{
DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
pool.release();
}
Enumeration allDrivers = drivers.elements();
while (allDrivers.hasMoreElements())
{
Driver driver = (Driver) allDrivers.nextElement();
try {
DriverManager.deregisterDriver(driver);

log("撤銷JDBC驅動程式 " + driver.getClass().getName()+"的註冊");
}
catch (SQLException e)
{
log(e, "無法撤銷下列JDBC驅動程式的註冊: " + driver.getClass().getName());
}
}
}

/**
* 根據指定屬性建立串連池執行個體.
*
* @param props 串連池屬性
*/
private void createPools(Properties props)
{
Enumeration propNames = props.propertyNames();
while (propNames.hasMoreElements())
{
String name = (String) propNames.nextElement();
if (name.endsWith(".url")) {
String poolName = name.substring(0, name.lastIndexOf("."));
String url = props.getProperty(poolName + ".url");
if (url == null) {
log("沒有為串連池" + poolName + "指定URL");
continue;
}
String user = props.getProperty(poolName + ".user");
String password = props.getProperty(poolName + ".password");
String maxconn = props.getProperty(poolName + ".maxconn", "0");
int max;
try{
max = Integer.valueOf(maxconn).intValue();
}
catch (NumberFormatException e)
{
log("錯誤的最大串連數限制: " + maxconn + " .串連池: " + poolName);
max = 0;
}
DBConnectionPool pool = new DBConnectionPool(poolName, url, user, password, max);
pools.put(poolName, pool);
log("成功建立串連池" + poolName);
}
}
}

/**
* 讀取屬性完成初始化
*/
private void init()
{
try
{
Properties p = new Properties();
String configs = System.getProperty("user.dir")+"//conf//db.properties";

System.out.println("configs file local at "+configs);
FileInputStream is = new FileInputStream(configs);
Properties dbProps = new Properties();
try
{
dbProps.load(is);
}
catch (Exception e)
{
System.err.println("不能讀取屬性檔案. " +"請確保db.properties在CLASSPATH指定的路徑中");
return;
}
String logFile = dbProps.getProperty("logfile", "DBConnectionManager.log");
try{

log = new PrintWriter(new FileWriter(logFile, true), true);
}
catch (IOException e)
{
System.err.println("無法開啟記錄檔: " + logFile);
log = new PrintWriter(System.err);
}
loadDrivers(dbProps);
createPools(dbProps); }catch(Exception e){}
}

/**
171 * 裝載和註冊所有JDBC驅動程式
172 *
173 * @param props 屬性
174 */
private void loadDrivers(Properties props)
{
String driverClasses = props.getProperty("drivers");
StringTokenizer st = new StringTokenizer(driverClasses);
while (st.hasMoreElements())
{
String driverClassName = st.nextToken().trim();
try{
Driver driver = (Driver)
Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
drivers.addElement(driver);
System.out.println(driverClassName);
log("成功註冊JDBC驅動程式" + driverClassName);
}
catch (Exception e)
{
log("無法註冊JDBC驅動程式: " +
driverClassName + ", 錯誤: " + e);
}
}
}

/**
* 將文本資訊寫入記錄檔
*/
private void log(String msg)
{
log.println(new Date() + ": " + msg);
}

/**
* 將文本資訊與異常寫入記錄檔
*/
private void log(Throwable e, String msg)
{
log.println(new Date() + ": " + msg);
e.printStackTrace(log);
}

/**
* 此內部類定義了一個串連池.它能夠根據要求建立新串連,直到預定的最
* 大串連數為止.在返回串連給客戶程式之前,它能夠驗證串連的有效性.
*/

class DBConnectionPool
{
//private int checkedOut;
private Vector freeConnections = new Vector();
private int maxConn;
private String name;
private String password;
private String URL;
private String user;

/**
* 建立新的串連池
*
* @param name 串連池名字
* @param URL 資料庫的JDBC URL
* @param user 資料庫帳號,或 null
* @param password 密碼,或 null
* @param maxConn 此串連池允許建立的最大串連數
*/
public DBConnectionPool(String name, String URL, String user, String password,int maxConn)
{
this.name = name;
this.URL = URL;
this.user = user;
this.password = password;
this.maxConn = maxConn;
}
/**
* 將不再使用的串連返回給串連池
*
* @param con 客戶程式釋放的串連
*/
public synchronized void freeConnection(Connection con) {
// 將指定串連加入到向量末尾
try
{
if(con.isClosed()){System.out.println("before freeConnection con is closed");}
freeConnections.addElement(con);
Connection contest = (Connection) freeConnections.lastElement();
if(contest.isClosed()){System.out.println("after freeConnection contest is closed");}
notifyAll();
}catch(SQLException e){System.out.println(e);}
}

/**
* 從串連池獲得一個可用串連.如沒有閒置串連且當前串連數小於最大串連
* 數限制,則建立新串連.如原來登記為可用的串連不再有效,則從向量刪除之,
* 然後遞迴調用自己以嘗試新的可用串連.
*/
public synchronized Connection getConnection()
{
Connection con = null;
if (freeConnections.size() > 0)
{
// 擷取向量中第一個可用串連
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
try {
if (con.isClosed())
{
log("從串連池" + name+"刪除一個無效串連");
System.out.println("從串連池" + name+"刪除一個無效串連");
// 遞迴調用自己,嘗試再次擷取可用串連
con = getConnection();
}
}
catch (SQLException e)
{
log("從串連池" + name+"刪除一個無效串連時錯誤");
System.out.println("從串連池" + name+"刪除一個無效串連出錯");
// 遞迴調用自己,嘗試再次擷取可用串連
con = getConnection();
}
if(freeConnections.size()>maxConn)
{ System.out.println(" 刪除一個溢出串連 ");
releaseOne();
}
}


else if((maxConn == 0)||(freeConnections.size()<maxConn))
{
con = newConnection();
}

return con;
}

public synchronized Connection returnConnection()
{
Connection con = null;
//如果閑置小於最大串連,返回一個新串連
if(freeConnections.size()<maxConn)
{
con = newConnection();
}
//如果閑置大於最大串連,返回一個可用的舊串連
else if(freeConnections.size()>=maxConn)
{

con = (Connection) freeConnections.firstElement();
System.out.println(" [a 串連池可用串連數 ] : "+"[ "+freeConnections.size()+" ]");
freeConnections.removeElementAt(0);
System.out.println(" [b 串連池可用串連數 ] : "+"[ "+freeConnections.size()+" ]");
try
{
if (con.isClosed())
{
log("從串連池" + name+"刪除一個無效串連");
System.out.println("從串連池" + name+"刪除一個無效串連");
returnConnection();
}
}catch (SQLException e)
{
log("從串連池" + name+"刪除一個無效串連時錯誤");
System.out.println("從串連池" + name+"刪除一個無效串連出錯");
returnConnection();
}
}
return con;
}

/**
* 從串連池擷取可用串連.可以指定客戶程式能夠等待的最長時間
* 參見前一個getConnection()方法.
*
* @param timeout 以毫秒計的等待時間限制
*/
public synchronized Connection getConnection(long timeout)
{
long startTime = new Date().getTime();
Connection con;
while ((con = getConnection()) == null)
{
try
{
wait(timeout);
}
catch (InterruptedException e) {}
if ((new Date().getTime() - startTime) >= timeout) {
// wait()返回的原因是逾時
return null;
}
}
return con;
}

/**
* 關閉所有串連
*/
public synchronized void release()
{
Enumeration allConnections = freeConnections.elements();
while (allConnections.hasMoreElements())
{
Connection con = (Connection) allConnections.nextElement();
try {
con.close();
log("關閉串連池" + name+"中的一個串連");
}
catch (SQLException e)
{
log(e, "無法關閉串連池" + name+"中的串連");
}
}
freeConnections.removeAllElements();
}
/**
* 關閉一個串連
*/
public synchronized void releaseOne()
{
if(freeConnections.firstElement()!=null)
{ Connection con = (Connection) freeConnections.firstElement();
try {
con.close();
System.out.println("關閉串連池" + name+"中的一個串連");
log("關閉串連池" + name+"中的一個串連");
}
catch (SQLException e)
{

System.out.println("無法關閉串連池" + name+"中的一個串連");
log(e, "無法關閉串連池" + name+"中的串連");
}
}
else
{
System.out.println("releaseOne() bug.......................................................");

}
}

/**
* 建立新的串連
*/
private Connection newConnection()
{
Connection con = null;
try
{
if (user == null) {
con = DriverManager.getConnection(URL);
}
else{
con = DriverManager.getConnection(URL, user, password);
}
log("串連池" + name+"建立一個新的串連");

}
catch (SQLException e) {
log(e, "無法建立下列URL的串連: " + URL);
return null;
}
return con;
}
}
}

================================
/**
* Title: ConnectPool.java
* Description: 資料庫操作
* Copyright: Copyright &copy; 2002/12/25
* Company:
* Author :
* remark : 加入指標復原
* Version 2.0
*/

import java.io.*;
import com.sjky.pool.*;
import java.sql.*;
import java.util.*;
import java.util.Date;
import java.net.*;

public class PoolMan extends ConnectPool {

private ConnectPool connMgr;
private Statement stmt;
private Connection con ;
private ResultSet rst;

/**
*對象串連初始化
* */

public Connection getPool(String name) throws Exception
{
try{
connMgr = ConnectPool.getInstance();
con = connMgr.getConnection(name);
}catch(Exception e)
{
System.err.println("不能建立串連!請嘗試重啟應用伺服器");

}
return con;
}

/**
*同以上方法,加入串連空閑等待時間
*待用方法
* */

public Connection getPool_t(String name, long time) throws Exception
{
try{
connMgr = ConnectPool.getInstance();
con = connMgr.getConnection(name,time);
}catch(Exception e)
{
System.err.println("不能建立串連!");

}
return con;
}
/**
*執行查詢方法1
* */
public ResultSet executeQuery(String SqlStr) throws Exception
{
ResultSet result = null;
try
{
stmt = con.createStatement();
result = stmt.executeQuery(SqlStr);
// here add one line by jnma 12.11
con.commit();
}
catch(java.sql.SQLException e)
{
throw new Exception("執行查詢語句出錯");
}
return result;
}
/**
*執行查詢方法2
* */
public ResultSet getRst(String SqlStr) throws Exception
{
// ResultSet result = null;
try
{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rst = stmt.executeQuery(SqlStr);
// here add one line by jnma 12.11
con.commit();
}
catch(java.sql.SQLException e)
{
throw new Exception("執行查詢語句出錯");
}
return rst;
}
/**
*執行更新
* */
public int Update(String SqlStr) throws Exception
{
int result = -1;
try
{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
result = stmt.executeUpdate(SqlStr);
// here add one line by jnma 12.11
con.commit();
if(result==0)
System.out.println("執行delete,update,insert SQL出錯");
}
catch(java.sql.SQLException e)
{
System.err.println("執行delete,update,insert SQL出錯");
}
return result;
}

/**
*執行交易處理
* */
public boolean handleTransaction(Vector SqlArray) throws Exception
{
boolean result = false;
int ArraySize = SqlArray.size();
try
{
stmt = con.createStatement();
con.setAutoCommit(false);
System.out.println("ArraySize is" +ArraySize);
for(int i=0;i<ArraySize;i++)
{
System.out.println(" 開始執行語句"+(String)SqlArray.elementAt(i));
stmt.executeUpdate((String)SqlArray.elementAt(i));
System.out.println(" 執行成功");
}
con.commit();
con.setAutoCommit(true) ;//必須
System.out.println("事務執行成功");
result = true;
}
catch(java.sql.SQLException e)
{
try
{
System.out.println(e.toString());
System.out.println("資料庫操作失敗");
con.rollback();
}
catch(java.sql.SQLException Te)
{
System.err.println("事務出錯復原異常");
}
}
try
{
con.setAutoCommit(true);
}
catch(java.sql.SQLException e)
{
System.err.println("設定自動認可失敗");
}
return result;
}

/**
*釋放串連
* */
public void close(String name) throws Exception
{
try
{
if(stmt!=null)
stmt.close();
if(con!=null)
{
connMgr.freeConnection(name,con);

System.out.println(" [c 正在釋放一個串連 ] ");

}
}
catch(java.sql.SQLException e)
{
System.err.println("釋放串連出錯");
}
}

}
===========================
屬性檔案db.properties放在conf下

#drivers=com.inet.tds.TdsDriver
#logfile=c://resin-2.1.4//DBConnectPool-log.txt
#test.maxconn=1000
#test.url=jdbc:inetdae:SERVER:1433?sql7=true
#test.user=sa
#test.password=test

drivers=com.microsoft.jdbc.sqlserver.SQLServerDriver
logfile=F://resin-2.1.4//DBConnectPool-log.txt
test.maxconn=20
test.url=jdbc:microsoft:sqlserver://192.168.0.5:1433;DatabaseName=test
test.user=sa
test.password=test


#drivers=oracle.jdbc.driver.OracleDriver
#logfile=c://resin-2.1.4//DBConnectPool-log.txt
#test.maxconn=100
#test.url=jdbc:oracle:thin:@192.168.0.10:1521:myhome
#test.user=system
#test.password=manager
#mysql端3306

#drivers=org.gjt.mm.mysql.Driver
#logfile=c://resin-2.1.4//DBConnectPool-log.txt
#test.maxconn=100
#test.url=jdbc:mysql://192.168.0.4:3306/my_test
#test.user=root
#test.password=system

功能完善的Java串連池調用執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.