1. 程式人生 > >Redis連接池

Redis連接池

localhost sleep lis 當前 mysq return object c name 代碼塊

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)
}
}

Redis連接池