Skip to content

Instantly share code, notes, and snippets.

@vituchon
Created June 2, 2020 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vituchon/d5058f6123e1b1d6d82ac5d228f8a767 to your computer and use it in GitHub Desktop.
Save vituchon/d5058f6123e1b1d6d82ac5d228f8a767 to your computer and use it in GitHub Desktop.
package util
import com.redis._
import java.util.concurrent.Executors
import scala.concurrent.{Future, ExecutionContext}
trait Cache {
def get(key: String): Future[Option[String]]
def set(key: String, value: String, seconds: Long): Future[Boolean]
def ping(): Future[Boolean]
def pushToQueue(queueName: String, data: String): Future[Option[Long]]
}
class RedisCache extends Cache {
private val Ex = Executors.newFixedThreadPool(5)
private implicit val Ec = ExecutionContext.fromExecutor(Ex)
lazy val clients = new RedisClientPool(Configuration.CacheHost, Configuration.CachePort)
def get(key: String): Future[Option[String]] = {
val result = Future { clients.withClient(_.get(key)) }
result
}
def set(key: String, value: String, seconds: Long = 0): Future[Boolean] = {
val result = if (seconds <= 0) {
Future { clients.withClient(_.set(key, value)) }
} else {
Future { clients.withClient(_.setex(key, seconds, value)) }
}
result
}
def ping(): Future[Boolean] = Future {
clients.withClient { client =>
client.ping.exists(_ == "PONG")
}
} recover {
case _ => false
}
def pushToQueue(queueName: String, data: String): Future[Option[Long]] = {
Future { clients.withClient(_.rpush(queueName, data)) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment