通过包装类实现连接池

package com.mysql.utils;

import java.io.PrintWriter;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.logging.Logger;

import javax.sql.DataSource;


public class DatabaseSource implements DataSource {
 // 声明一个池管理对象
 private LinkedList pool = new LinkedList();
 // 在初始化这个类子类时在构造方法中实现设置多个连接
 public DatabaseSource() {
  try {
   Class.forName("com.mysql.jdbc.Driver");
   String url = "jdbc:mysql://127.0.0.1:1306/mydb1?useUnicode=true&characterEncoding=UTF-8";
   for (int i = 0; i < 3; i++) {// 创建原生连接
    Connection conn = DriverManager.getConnection(url, "root",
      "root");
    MyConn myConn = new MyConn(conn);
    // 放入连接池
    pool.add(myConn);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 // 返回一个连接,继承于DataSource
 public Connection getConnection() throws SQLException {
  synchronized (pool) {
   if (pool.size() == 0) {
    try {
     pool.wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    return getConnection();
   }
   return pool.removeFirst();
  }
 }
 // 包装connection
 class MyConn implements Connection {
  // 声明被包装的成员
  private Connection conn;

  // 构造接收MySql的connection的对象
  public MyConn(Connection conn) {
   this.conn = conn;
  }

  // 关闭连接
  public void close() throws SQLException {
   synchronized (pool) {
    pool.add(this);
    pool.notify();
   }
  }

  public T unwrap(Class iface) throws SQLException {
   return conn.unwrap(iface);
  }

  public boolean isWrapperFor(Class

你可能感兴趣的:(通过包装类实现连接池)