diff --git a/build.sbt b/build.sbt index d590208..05a8389 100644 --- a/build.sbt +++ b/build.sbt @@ -33,6 +33,7 @@ lazy val root = `zio-quickstart-graphql-webservice`, `zio-quickstart-streams`, `zio-quickstart-encode-decode-json`, + `zio-quickstart-cache`, `zio-quickstart-prelude` ) @@ -49,4 +50,5 @@ lazy val `zio-quickstart-graphql-webservice` = project lazy val `zio-quickstart-streams` = project lazy val `zio-quickstart-encode-decode-json` = project lazy val `zio-quickstart-reloadable-services` = project +lazy val `zio-quickstart-cache` = project lazy val `zio-quickstart-prelude` = project diff --git a/zio-quickstart-cache/build.sbt b/zio-quickstart-cache/build.sbt new file mode 100644 index 0000000..cee0731 --- /dev/null +++ b/zio-quickstart-cache/build.sbt @@ -0,0 +1,3 @@ +scalaVersion := "2.13.13" + +libraryDependencies += "dev.zio" %% "zio-cache" % "0.2.3" diff --git a/zio-quickstart-cache/src/main/scala/dev/zio/quickstart/CacheApp.scala b/zio-quickstart-cache/src/main/scala/dev/zio/quickstart/CacheApp.scala new file mode 100644 index 0000000..7bf2395 --- /dev/null +++ b/zio-quickstart-cache/src/main/scala/dev/zio/quickstart/CacheApp.scala @@ -0,0 +1,43 @@ +package dev.zio.quickstart + +import zio._ +import zio.cache.{Cache, Lookup} +import java.time.temporal.ChronoUnit + +object CacheApp extends ZIOAppDefault { + private val key = "key1" + + private def timeConsumingEffect(key: String) = + ZIO.sleep(5.seconds).as(key.hashCode) + + def run = + for { + cache <- Cache.make( + capacity = 100, + timeToLive = Duration.Infinity, + lookup = Lookup(timeConsumingEffect) + ) + _ <- Console.printLine(s"Start getting results by $key:") + startTime <- Clock.currentTime(ChronoUnit.SECONDS) + result <- cache + .get(key) + .zipPar(cache.get(key)) + .zipPar(cache.get(key)) + endTime <- Clock.currentTime(ChronoUnit.SECONDS) + _ <- ZIO.debug( + s"Result of parallel execution of three effects with $key: $result" + ) + + hits <- cache.cacheStats.map(_.hits) + misses <- cache.cacheStats.map(_.misses) + keyLastLoadedTimeOpt <- cache.entryStats(key) + keyLastLoadedTime <- ZIO.fromOption(keyLastLoadedTimeOpt).map(_.loaded) + _ <- ZIO.debug(s"Number of cache hits: $hits") + _ <- ZIO.debug(s"Number of cache misses: $misses") + _ <- ZIO.debug(s"The last time of getting $key: $keyLastLoadedTime") + _ <- ZIO.debug( + s"Time to get result by $key 3 times: ${endTime - startTime} seconds" + ) + } yield () + +}