package com.qf.spark.scala
import java.sql.{Connection, DriverManager}
import java.util
/**
* 连接池
*/
object ConnectionPoolUtil {
/**
* 需要设置的连接池数据
*/
private val max = 20 //连接池连接总数
private val connectionNum = 10 //每次产生连接数
private val pool = new util.LinkedList[Connection]() //连接池
private var conNum = 0 //当前连接池已经产生的连接数
//获取连接
def getConnections():Connection ={
//同步代码块
AnyRef.synchronized({
if(pool.isEmpty){
//加载驱动
GetConn
for(i<- 1 to connectionNum){
val conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hadoop",
"root",
"123"
)
pool.push(conn)
conNum += 1
}
}
pool.poll()
})
}
//加载驱动
def GetConn(): Unit ={
//控制加载
if(conNum < max && pool.isEmpty){
Class.forName("com.mysql.jdbc.Driver")
}else if (conNum>=max && pool.isEmpty){
println("Jdbc Pool has no connection now,please wait a moments!")
Thread.sleep(2000)
GetConn
}
}
def returnConn(conn:Connection): Unit ={
pool.push(conn)
}
}