Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add zio-cache quickstart #47

Merged
merged 1 commit into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 ()

}
Loading