Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.sunbird.cache.util

import org.sunbird.common.Platform
import org.sunbird.telemetry.logger.TelemetryManager
import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig}

/**
Expand All @@ -14,6 +15,8 @@ trait RedisConnector {
private val INDEX = Platform.getInteger("redis.dbIndex", 0)
private val jedisPool: JedisPool = new JedisPool(getConfig(), HOST, PORT)

registerShutdownHook()

/**
* This Method Returns a connection object from connection pool.
*
Expand All @@ -28,21 +31,45 @@ trait RedisConnector {
}

/**
* This Method takes a connection object and put it back to pool.
* This Method takes a connection object and returns it to pool.
* Uses jedis.close() which is the modern, non-deprecated approach
* and correctly returns the connection to the pool (or closes it if broken).
*
* @param jedis
*/
protected def returnConnection(jedis: Jedis): Unit = {
try if (null != jedis) jedisPool.returnResource(jedis)
catch {
case e: Exception => throw e
if (null != jedis) {
try jedis.close()
catch {
case e: Exception => TelemetryManager.error("Error returning Redis connection to pool: " + e.getMessage, e)
}
}
}

/**
* Closes the JedisPool, releasing all connections.
* Called automatically via the JVM shutdown hook.
*/
def closePool(): Unit = {
if (jedisPool != null && !jedisPool.isClosed) {
try jedisPool.close()
catch {
case e: Exception => TelemetryManager.error("Error closing JedisPool: " + e.getMessage, e)
}
}
}

private def registerShutdownHook(): Unit = {
Runtime.getRuntime.addShutdownHook(new Thread(() => {
TelemetryManager.log("Shutting down RedisConnector — closing connection pool")
closePool()
}))
}

private def getConfig(): JedisPoolConfig = {
val config: JedisPoolConfig = new JedisPoolConfig()
config.setMaxTotal(MAX_CONNECTIONS)
config.setBlockWhenExhausted(true);
config.setBlockWhenExhausted(true)
config
}
}