|
// Tiny Redis (Jedis) client wrapper for ZIO with Scala 3. |
|
// - Oto Brglez - <[email protected]> - May 2025 |
|
|
|
import redis.clients.jedis.*, redis.clients.jedis.params.* |
|
import zio.*, zio.ZIO.* |
|
import java.util.List as JavaList |
|
import scala.concurrent.duration.*, scala.jdk.CollectionConverters.* |
|
|
|
final case class Redis private (private val pool: JedisPool): |
|
private type Binary = Array[Byte] |
|
private type TTL = FiniteDuration |
|
private given Conversion[TTL, Long] = _.toSeconds.toInt |
|
private given Conversion[JavaList[Binary], List[Binary]] = _.asScala.toList |
|
private given Conversion[TTL, SetParams] = new SetParams().nx().ex(_) |
|
private given Conversion[TTL, GetExParams] = new GetExParams().ex(_) |
|
|
|
private def wPool[A](f: Jedis => Task[A]): Task[A] = |
|
acquireReleaseWith(attempt(pool.getResource))(r => attempt(r.close()).orElse(unit))(f) |
|
|
|
private def redis[A](r: => Jedis => A): Task[A] = wPool(redis => attempt(r(redis))) |
|
|
|
def get(key: Binary): Task[Option[Binary]] = redis(r => Option(r.get(key))) |
|
def get(key: String): Task[Option[String]] = redis(r => Option(r.get(key))) |
|
def set(key: Binary, value: Binary, params: SetParams): Task[String] = redis(_.set(key, value, params)) |
|
def set(key: Binary, value: Binary, ttl: TTL): Task[String] = redis(_.set(key, value, ttl)) |
|
def set(key: Binary, value: Binary): Task[String] = redis(_.set(key, value)) |
|
def getEx(key: Binary, ttl: TTL): Task[Option[Binary]] = redis(r => Option(r.getEx(key, ttl))) |
|
def mGet(keys: Binary*): Task[List[Array[Byte]]] = redis(_.mget(keys*)) |
|
def flushDb: Task[String] = redis(_.flushDB()) |
|
def flushAll: Task[String] = redis(_.flushAll()) |
|
|
|
object Redis: |
|
def live: TaskLayer[Redis] = ZLayer.scoped: |
|
for |
|
redisUri <- AppConfig.redisUri |
|
poolConfig <- |
|
succeed: |
|
val poolConfig = new JedisPoolConfig() |
|
poolConfig.setMaxTotal(8) |
|
poolConfig.setMaxIdle(8) |
|
poolConfig |
|
pool <- fromAutoCloseable(attemptBlocking(new JedisPool(poolConfig, redisUri))) |
|
yield Redis(pool) |
|
|
|
// Usage example,... |
|
def usage = { |
|
for |
|
redis <- ZIO.service[Redis] |
|
_ <- redis.flushAll |
|
_ <- redis.set("name".getBytes, "Oto".getBytes) |
|
_ <- redis.get("name") |
|
yield () |
|
}.provide(Redis.live) |