ITeye博客

[转帖]java数据库链接池

abei1 · 2007-08-10 10:30 · 数据库 · Markdown

首先说明一下,这个数据库链接池不是我写的。是我在网上找到的,由于代码并不全,因此进行了一些填充。可以正常运行了。所以贴出来希望能帮到需要的人。

       这个数据库链接池的好处在于当用户从数据库链接池中的到连接后,并不需要特殊的方法将链接关闭,直接用close方法就可以关闭了。废话少说,上代码!!!!

      再次说明一下,以下的代码是根据网上得到的部分代码填充得到的,并不代表没有错误。如果那位高手能将代码完善感激不尽。

     下面的一段代码是一些数据库的属性。

java 代码

  1. public class ConnectionParam {
  2. private String driver = null;                                //数据库驱动程序
  3. private String host = null;                                        //数据连接的URL
  4. private String user = null;                                        //数据库用户名
  5. private String password = null;                                //数据库密码
  6. private String dataBase= null;
  7. private String url = null;
  8. private int minConnection = 0;                //初始化连接数
  9. private int maxConnection = 0;                //最大连接数
  10. private long timeoutValue = 0;            //连接的最大空闲时间
  11. private long waitTime = 0;                //取连接的时候如果没有可用连接最大的等待时间
  12. public ConnectionParam(){
  13. super();
  14. try {
  15. String tmp = null;
  16. int value = 0;
  17. //CommonUtil.getPropertie("");方法是自己写的一个从属性文件中读取信息的方法。
  18. this.driver = CommonUtil.getPropertie("driver");
  19. this.host = CommonUtil.getPropertie("host");
  20. this.user = CommonUtil.getPropertie("user");
  21. this.password = CommonUtil.getPropertie("password");
  22. this.dataBase= CommonUtil.getPropertie("dataBase");
  23. this.url =CommonUtil.getPropertie("url");
  24. tmp = CommonUtil.getPropertie("maxConnection");
  25. value = 0;
  26. if(CommonUtil.isNull(tmp)){
  27. value = 0;
  28. }else{
  29. value = Integer.parseInt(tmp);
  30. }
  31. this.maxConnection = value;
  32. tmp = CommonUtil.getPropertie("timeoutValue");
  33. value = 0;
  34. if(CommonUtil.isNull(tmp)){
  35. value = 0;
  36. }else{
  37. value = Integer.parseInt(tmp);
  38. }
  39. this.timeoutValue = value;
  40. tmp = CommonUtil.getPropertie("waitTime");
  41. value = 0;
  42. if(CommonUtil.isNull(tmp)){
  43. value = 0;
  44. }else{
  45. value = Integer.parseInt(tmp);
  46. }
  47. this.waitTime = value;
  48. } catch (IOException e) {
  49. // TODO Auto-generated catch block
  50. e.printStackTrace();
  51. }
  52. }
  53. }

    下面这段代码是实现连接池的,其中的一些方法并没有实现。请各位见谅。

java 代码

  1. import java.io.PrintWriter;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import javax.sql.DataSource;
  9. public class DataSourceImpl implements DataSource {
  10. private ConnectionParam connParam = null;
  11. private List conns = null;
  12. public DataSourceImpl(ConnectionParam param){
  13. conns = new ArrayList();
  14. this.connParam = param;
  15. }
  16. public Connection getConnection() throws SQLException {
  17. //首先从连接池中找出空闲的对象
  18. Connection conn = getFreeConnection(0);
  19. Connection conn2 = null;
  20. if(conn == null){
  21. //判断是否超过最大连接数,如果超过最大连接数
  22. //则等待一定时间查看是否有空闲连接,否则抛出异常告诉用户无可用连接
  23. if(getConnectionCount() >= connParam.getMaxConnection())
  24. conn = getFreeConnection(connParam.getWaitTime());
  25. else{//没有超过连接数,重新获取一个数据库的连接
  26. try {
  27. Class.forName(connParam.getDriver()).newInstance();
  28. conn2 = DriverManager.getConnection(connParam.getUrl(),
  29. connParam.getUser(), connParam.getPassword());
  30. } catch (InstantiationException e) {
  31. e.printStackTrace();
  32. } catch (IllegalAccessException e) {
  33. e.printStackTrace();
  34. } catch (ClassNotFoundException e) {
  35. e.printStackTrace();
  36. }
  37. //代理将要返回的连接对象
  38. _Connection _conn = new _Connection(conn2,true);
  39. synchronized(conns){
  40. conns.add(_conn);
  41. }
  42. conn = _conn.getConnection();
  43. }
  44. }
  45. return conn;
  46. }
  47. public Connection getConnection(String username, String password)
  48. throws SQLException {
  49. //首先从连接池中找出空闲的对象
  50. Connection conn = getFreeConnection(0);
  51. Connection conn2 = null;
  52. if(conn == null){
  53. //判断是否超过最大连接数,如果超过最大连接数
  54. //则等待一定时间查看是否有空闲连接,否则抛出异常告诉用户无可用连接
  55. if(getConnectionCount() >= connParam.getMaxConnection())
  56. conn = getFreeConnection(connParam.getWaitTime());
  57. else{//没有超过连接数,重新获取一个数据库的连接
  58. connParam.setUser(username);
  59. connParam.setPassword(password);
  60. try {
  61. Class.forName(connParam.getDriver()).newInstance();
  62. conn2 = DriverManager.getConnection(connParam.getUrl(),
  63. username, password);
  64. } catch (InstantiationException e) {
  65. // TODO Auto-generated catch block
  66. e.printStackTrace();
  67. } catch (IllegalAccessException e) {
  68. // TODO Auto-generated catch block
  69. e.printStackTrace();
  70. } catch (ClassNotFoundException e) {
  71. // TODO Auto-generated catch block
  72. e.printStackTrace();
  73. }
  74. //代理将要返回的连接对象
  75. _Connection _conn = new _Connection(conn2,true);
  76. synchronized(conns){
  77. conns.add(_conn);
  78. }
  79. conn = _conn.getConnection();
  80. }
  81. }
  82. return conn;
  83. }
  84. public PrintWriter getLogWriter() throws SQLException {
  85. // TODO Auto-generated method stub
  86. return null;
  87. }
  88. public int getLoginTimeout() throws SQLException {
  89. // TODO Auto-generated method stub
  90. return 0;
  91. }
  92. public void setLogWriter(PrintWriter out) throws SQLException {
  93. // TODO Auto-generated method stub
  94. }
  95. public void setLoginTimeout(int seconds) throws SQLException {
  96. // TODO Auto-generated method stub
  97. }
  98. public void initConnection(){
  99. //       TODO Auto-generated method stub
  100. }
  101. public void stop(){
  102. //       TODO Auto-generated method stub
  103. }
  104. /**
  105. * 从连接池中取一个空闲的连接
  106. * @param nTimeout        如果该参数值为0则没有连接时只是返回一个null
  107. * 否则的话等待nTimeout毫秒看是否还有空闲连接,如果没有抛出异常
  108. * @return Connection
  109. * @throws SQLException
  110. */
  111. protected synchronized Connection getFreeConnection(long nTimeout)
  112. throws SQLException
  113. {
  114. Connection conn = null;
  115. Iterator iter = conns.iterator();
  116. while(iter.hasNext()){
  117. _Connection _conn = (_Connection)iter.next();
  118. if(!_conn.isInUse()){
  119. conn = _conn.getConnection();
  120. _conn.setInUse(true);
  121. break;
  122. }
  123. }
  124. if(conn == null && nTimeout > 0){
  125. //等待nTimeout毫秒以便看是否有空闲连接
  126. try{
  127. Thread.sleep(nTimeout);
  128. }catch(Exception e){}
  129. conn = getFreeConnection(0);
  130. if(conn == null)
  131. throw new SQLException("没有可用的数据库连接");
  132. }
  133. return conn;
  134. }
  135. /**
  136. * 关闭该连接池中的所有数据库连接
  137. * @return int 返回被关闭连接的个数
  138. * @throws SQLException
  139. */
  140. public int close() throws SQLException
  141. {
  142. int cc = 0;
  143. SQLException excp = null;
  144. Iterator iter = conns.iterator();
  145. while(iter.hasNext()){
  146. try{
  147. ((_Connection)iter.next()).close();
  148. cc ++;
  149. }catch(Exception e){
  150. if(e instanceof SQLException)
  151. excp = (SQLException)e;
  152. }
  153. }
  154. if(excp != null)
  155. throw excp;
  156. return cc;
  157. }
  158. /**
  159. * 返回当前链接的个数
  160. * @return
  161. */
  162. private int getConnectionCount(){
  163. Iterator iter = conns.iterator();
  164. int count = 0;
  165. while(iter.hasNext()){
  166. _Connection _conn = (_Connection)iter.next();
  167. if(_conn.isInUse()){
  168. count++;
  169. }
  170. }
  171. return count;
  172. }
  173. }

下面的是一个代理类。用来实现直接用close关闭连接。

java 代码

  1. import java.lang.reflect.InvocationHandler;
  2. import java.lang.reflect.Method;
  3. import java.lang.reflect.Proxy;
  4. import java.sql.Connection;
  5. import java.sql.SQLException;
  6. public class _Connection implements InvocationHandler {
  7. private final static String CLOSE_METHOD_NAME = "close";
  8. private Connection conn = null;
  9. //数据库的忙状态
  10. private boolean inUse = false;
  11. //用户最后一次访问该连接方法的时间
  12. private long lastAccessTime = System.currentTimeMillis();
  13. _Connection(Connection conn, boolean inUse){
  14. this.conn = conn;
  15. this.inUse = inUse;
  16. }
  17. /**
  18. * Returns the conn.
  19. * @return Connection
  20. */
  21. public Connection getConnection() {
  22. //返回数据库连接conn的接管类,以便截住close方法
  23. Connection conn2 = (Connection)Proxy.newProxyInstance(
  24. conn.getClass().getClassLoader(),
  25. conn.getClass().getInterfaces(),this);
  26. return conn2;
  27. }
  28. /**
  29. * 该方法真正的关闭了数据库的连接
  30. * @throws SQLException
  31. */
  32. void close() throws SQLException{
  33. //由于类属性conn是没有被接管的连接,因此一旦调用close方法后就直接关闭连接
  34. conn.close();
  35. }
  36. /**
  37. * Returns the inUse.
  38. * @return boolean
  39. */
  40. public boolean isInUse() {
  41. return inUse;
  42. }
  43. /**
  44. * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object)
  45. */
  46. public Object invoke(Object proxy, Method m, Object[] args)
  47. throws Throwable
  48. {
  49. Object obj = null;
  50. //判断是否调用了close的方法,如果调用close方法则把连接置为无用状态
  51. if(CLOSE_METHOD_NAME.equals(m.getName()))
  52. setInUse(false);
  53. else
  54. obj = m.invoke(conn, args);
  55. //设置最后一次访问时间,以便及时清除超时的连接
  56. lastAccessTime = System.currentTimeMillis();
  57. return obj;
  58. }
  59. /**
  60. * Returns the lastAccessTime.
  61. * @return long
  62. */
  63. public long getLastAccessTime() {
  64. return lastAccessTime;
  65. }
  66. /**
  67. * Sets the inUse.
  68. * @param inUse The inUse to set
  69. */
  70. public void setInUse(boolean inUse) {
  71. &

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。