diff --git a/platform-core/platform-cache/src/main/scala/org/sunbird/cache/util/RedisConnector.scala b/platform-core/platform-cache/src/main/scala/org/sunbird/cache/util/RedisConnector.scala index 9300ab1b7..be15363e6 100644 --- a/platform-core/platform-cache/src/main/scala/org/sunbird/cache/util/RedisConnector.scala +++ b/platform-core/platform-cache/src/main/scala/org/sunbird/cache/util/RedisConnector.scala @@ -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} /** @@ -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. * @@ -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 } }