Java版简易版连接池:
import java.sql.Connection; import java.sql.DriverManager; import java.util.LinkedList; /** * 简易版的连接池 */ public class ConnectionPool { //静态的Connection private static LinkedList<Connection>connections; //加载驱动 static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //获取连接 多线程访问并发问题控制 public synchronized static Connection getConnectoin(){ try { if (connections==null){ connections=new LinkedList<Connection>(); for (int i =0;i<10;i++){ Connection conn=DriverManager.getConnection( "jdbc:mysql://localhost:3306/spark", "username", "password" ); connections.push(conn); } } }catch (Exception e){ e.printStackTrace(); } return connections.poll(); } /** * 还连接 * 返回连接 */ public static void returnConnection(Connection conn){ connections.push(conn); } }
scala版简易版连接池:
object ConnectionPoolUtil { /** * 需要设置的连接池数据 */ private val max=10//连接池总数 private val connectionNum=10//每次产生连接数 private val pool=new util.LinkedList[Connection]() private var conNum=0//当前连接池已经产生的连接数 //获取连接 def getConnections(): Connection ={ //同步代码块 AnyRef.synchronized({ //加载驱动 for(i<-1 to connectionNum){ val conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/spark", "username", "password" ) pool.push(conn) conNum+=1 } pool.poll() }) } //加载驱动 def GetConn(): Unit ={ //控制加载 if (conNum<max && pool.isEmpty){ Class.forName("com.mysql.jdbc.mysql.") }else if(conNum>=max&&pool.isEmpty){ println("Jdbc Pool had no connection now,please wait a moments") Thread.sleep(2000) GetConn() } } //还连接 def returnConn(conn:Connection): Unit ={ pool.push(conn) } }