I am trying to use Caffeine cache. How to create the object for the Caffeine cache using Java? I am not using any Spring for now in my project.
Based on Caffeine's official repository and wiki, Caffeine is a high performance Java 8 based caching library providing a near optimal hit rate. And it is inspired by Google Guava.
Because Caffeine is an in-memory cache it is quite simple to instantiate a cache object.
For example:
LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(key -> createExpensiveGraph(key));
Lookup an entry, or null if not found:
Graph graph = graphs.getIfPresent(key);
Lookup and compute an entry if absent, or null if not computable:
graph = graphs.get(key, k -> createExpensiveGraph(key));
Note: createExpensiveGraph(key) may be a DB getter or an actual computed graph.
Insert or update an entry:
graphs.put(key, graph);
Remove an entry:
graphs.invalidate(key);
EDIT: Thanks to @BenManes's suggestion, I'm adding the dependency:
Edit your pom.xml and add:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>1.0.0</version>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With