Skip to content

Instantly share code, notes, and snippets.

@michalkowol
Last active May 26, 2021 23:12
Show Gist options
  • Save michalkowol/e9d64b220af48d731645 to your computer and use it in GitHub Desktop.
Save michalkowol/e9d64b220af48d731645 to your computer and use it in GitHub Desktop.
import com.michalkowol.vip.model.bar.{ AppWithBrand, Brand, App }
import spray.caching.LruCache
import scala.concurrent.{ Future, ExecutionContext }
import scala.concurrent.duration.FiniteDuration
object CachingBarClientWrapper {
val defaultCacheDuration = FiniteDuration(30, "s")
}
trait CachingBarClientWrapper extends BarClient {
implicit def ec: ExecutionContext
def wrappedClient: BarClient
private[this] case class CacheKey(brandId: String, appId: String)
private[this] lazy val brandCache = LruCache.apply[Brand](timeToLive = cacheDuration)
private[this] lazy val appCache = LruCache.apply[App](timeToLive = cacheDuration)
private[this] lazy val appWithBrand = LruCache.apply[AppWithBrand](timeToLive = cacheDuration)
def cacheDuration: FiniteDuration = CachingBarClientWrapper.defaultCacheDuration
final override def getBrand(brandId: String): Future[Brand] =
brandCache(brandId) {
wrappedClient.getBrand(brandId)
}
final override def getApp(brandId: String, appId: String): Future[App] =
appCache(CacheKey(brandId, appId)) {
wrappedClient.getApp(brandId, appId)
}
final override def getBrandWithApp(brandId: String, appId: String): Future[AppWithBrand] =
appWithBrand(CacheKey(brandId, appId)) {
wrappedClient.getBrandWithApp(brandId, appId)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment