pool2
我在使用 Apache库的 Scala 中有以下代码。要池化的对象是OlapConnection
(一个olap4j
类,类似于 SQL 连接)。
问题是当池对象的数量超过最大值时,我无法让池自动关闭连接。
如果我将一个对象返回到pool.returnObject
触发passivateObject
. 如果我在 中关闭连接passivateObject
,我会在每次返回对象时关闭它,这不是我想要的 - 我需要缓存打开的连接。如果我不关闭中的连接passivateObject
,那么它将永远不会关闭。
如何使这项工作?
斯卡拉代码:
class OlapConnectionUtil (val pool: ObjectPool[OlapConnection]) {
def connect = {
pool.borrowObject
}
def close(olapConnection: OlapConnection) = {
pool.returnObject(olapConnection)
}
}
class OlapConnectionFactory extends BasePooledObjectFactory[OlapConnection] {
override def create = {
val connectionString = "jdbc:mondrian:Jdbc=jdbc:mysql://localhost:3306/foodmart?" +
"user=x&password=x;Catalog=FoodMart.xml;JdbcDrivers=com.mysql.jdbc.Driver"
val connection = DriverManager.getConnection(connectionString)
connection.unwrap(classOf[OlapConnection])
}
override def wrap(olapConnection: OlapConnection) =
new DefaultPooledObject(olapConnection)
override def passivateObject(pooledObject: PooledObject[OlapConnection] ) {
println("passivateObject WAS CALLED")
pooledObject.getObject.close
}
}
class Test {
val olapConnectionFactory = new OlapConnectionFactory
def test = {
val config = new GenericObjectPoolConfig
config.setMaxIdle(5)
config.setMaxTotal(10)
val util = new OlapConnectionUtil(
new GenericObjectPool[OlapConnection](olapConnectionFactory,config))
val olapConnection = util.connect
// do stuff with olapConnection
util.close(olapConnection)