All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.colisweb.simplecache.redis.RedisCache.scala Maven / Gradle / Ivy

The newest version!
package com.colisweb.simplecache.redis

import com.colisweb.simplecache.core.Cache
import com.colisweb.simplecache.redis.codec._
import redis.clients.jedis.util.Pool
import redis.clients.jedis.{Jedis, JedisPool}

import scala.concurrent.duration.FiniteDuration
import scala.util.Using

class RedisCache[Key, Value](pool: JedisPool, ttl: Option[FiniteDuration] = None)(
    keyEncoder: Encoder[Key],
    valueCodec: Codec[Value]
) extends Cache[Key, Value] {

  private val jedisPool: Pool[Jedis] = pool

  override def get(key: Key): Option[Value] =
    withJedis { jedis =>
      Option(jedis.get(keyEncoder.encode(key))).map(bytes => valueCodec.decode(bytes).get)
    }

  override def update(key: Key, value: Value): Unit =
    withJedis { jedis =>
      val keyBytes   = keyEncoder.encode(key)
      val valueBytes = valueCodec.encode(value)
      ttl match {
        case Some(time) => jedis.setex(keyBytes, time.toSeconds max 1, valueBytes)
        case None       => jedis.set(keyBytes, valueBytes)
      }
      ()
    }

  override def remove(key: Key): Unit =
    withJedis { jedis =>
      jedis.del(keyEncoder.encode(key))
      ()
    }

  override def clear(): Unit =
    withJedis { jedis =>
      jedis.flushDB()
      ()
    }

  private final def withJedis[V](task: Jedis => V): V =
    Using(jedisPool.getResource)(task).get

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy