Created
June 2, 2020 17:10
-
-
Save vituchon/d5058f6123e1b1d6d82ac5d228f8a767 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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