GithubHelp home page GithubHelp logo

stuartapp / zcaffeine Goto Github PK

View Code? Open in Web Editor NEW
9.0 46.0 1.0 88 KB

ZIO wrapper for the Caffeine library : https://github.com/ben-manes/caffeine

License: Apache License 2.0

Scala 71.72% Shell 28.28%
cache caffeine scala zio

zcaffeine's Introduction

zcaffeine: ZIO-friendly Caffeine wrapper

GitHub Workflow Status GitHub Maven Central Sonatype Nexus (Snapshots)

zcaffeine is a ZIO-friendly wrapper for the Caffeine cache library.

  • Built for ZIO 2
  • Available for Scala 2.13 and Scala 3

Setup

Add the library to your dependencies:

libraryDependencies += "com.stuart" %% "zcaffeine" % "1.0.0-M1"

Snapshots are also published on Sonatype’s snapshots repository.

Usage

The ZCaffeine object is the entrypoint for configuring your cache, by using either:

  • A CaffeineSpec, either in its string representation or already loaded
  • An unconfigured builder

Please note that setting that can be configured by a CaffeineSpec can also be configured from the builder, with the builder supporting more options:

  • Setting removal and/or evictions listeners
  • Dynamically setting the expiration of cache entries based on the key & value
  • Enabling scheduling of cache maintenance (rather than running maintenance on cache operations)
  • Compute a cache entry weight dynamically, based on the key & value

After configuration, the cache can be constructed through either:

  • build(): builds a "manually operated" Cache which requires the use of get(key, mappingFunction)/getAll(keys, mappingFunction)/put(key,value) to load or replace values in the cache
  • build(loadOne,loadAll,reloadOne): builds an "automated" LoadingCache cache which offers, along with the other methods from Cache, get(key)/getAll(keys)/refresh/refreshAll that defers to loadOne/loadAll,reloadAll to compute the cache entries

Note: loadAll and reloadOne are optional: both defer to loadOne if missing, but they can set if the behavior should differ (eg. parallel computation in loadAll)

Examples

Building a cache

// Configure a cache
val zcaffeine = ZCaffeine[Any, String, String]().map(
    _.initialCapacity(InitialCapacity(1))
      .maximumSize(MaxSize(10))
      .enableScheduling()
      .recordStats()
      .expireAfter(
        afterCreate = (key, _, _) => key.length.hour,
        afterUpdate = (key, _, _, _) => key.length.minutes,
        afterRead = (_, _, _, _) => Duration.Infinity
      )
  )
  
val getTime = ZIO.clockWith(_.instant)

// Create a Cache 
val cache = zcaffeine.flatMap(_.build())

// Create a LoadingCache
val loadingCache = zcaffeine.flatMap(
    _.build(
      loadOne = key => getTime.map(time => s"one::$key:$time"),
      loadAll = Some(keys => getTime.map(time => keys.map(key => (key, s"all::$key:$time")).toMap)),
      reloadOne = Some((key, oldValue) => getTime.map(time => s"reload::$key:$oldValue-->$time"))
    )
  )  

Using a cache

You can also find additional examples from zcaffeine’s tests.

/**********************************************/
/*               Using a Cache                */
/* Supposing cache = Cache[Any,String,String] */
/**********************************************/


// get or compute
cache.get("key")
// get all or compute all
cache.getAll("key1","key2"))(keys => ZIO.succeed(keys.map(key => (key, key + key)).toMap))
// get only if cached
cache.getIfPresent("key3")
// insert or replace
cache.put("key", ZIO.succeed("value1"))
// invalidate one
cache.invalidate("key")
// invalidate all
cache.invalidateAll
// invalidate all specified keys
cache.invalidateAll("key1","key2")


/*****************************************************/
/*               Using a LoadingCache                */
/* Supposing cache = LoadingCache[Any,String,String] */
/*****************************************************/

// get or compute using the functions set while building the cache
cache.get("key1")
// get all or compute all using the functions set while building the cache
cache.getAll(Set("key1","key2"))
// refresh using the functions set while building the cache and get
cache.refresh("key1")
// refresh all using the functions set while building the cache and get all
cache.refreshAll("key1","key2")

License

This project is published under the Apache 2.0 license.

zcaffeine's People

Contributors

aartigao avatar scala-steward avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

scala-steward

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.