Skip to content

Commit

Permalink
Merge pull request #47 from GrigoriiBerezin/add_zio_cache_quickstart
Browse files Browse the repository at this point in the history
feat: add zio-cache quickstart
  • Loading branch information
khajavi authored Apr 29, 2024
2 parents a412a92 + 74774f8 commit 33bb29c
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -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`
)

Expand All @@ -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
3 changes: 3 additions & 0 deletions zio-quickstart-cache/build.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
scalaVersion := "2.13.13"

libraryDependencies += "dev.zio" %% "zio-cache" % "0.2.3"
Original file line number Diff line number Diff line change
@@ -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 ()

}

0 comments on commit 33bb29c

Please sign in to comment.