3

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Bravo
  • 8,589
  • 14
  • 48
  • 85

1 Answers1

3

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));
  1. Lookup an entry, or null if not found:

    Graph graph = graphs.getIfPresent(key);
    
  2. 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.

  3. Insert or update an entry:

    graphs.put(key, graph);
    
  4. 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>
Gal Dreiman
  • 3,969
  • 2
  • 21
  • 40
  • i created a sample spring application , and in the java based configuration i created below Cache object cache = Caffeine.newBuilder().expireAfterWrite(24, TimeUnit.HOURS).build(); , tried to autowire this in service class like below @Autowire private Cache cache; but getting error that at least 1 Bean of type Cache must defined . Why this exception is getting ? i defined that type bean , any help please . – Bravo Mar 20 '17 at 12:35
  • @Bravo did you add the dependency (jar) to your build? For Spring you might want to look at their [sample](https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-cache) project. – Ben Manes Mar 20 '17 at 13:15
  • @Bravo You could look at one of the [examples](https://github.com/ben-manes/caffeine/tree/master/examples) for a self contained usage. We can add more based on suggestions. Spring isn't required and I'm not familiar with it enough to advise beyond their sample caching project. – Ben Manes Mar 20 '17 at 14:39
  • @Bravo All you need is `private final Cache graphs = Caffeine.newBuilder()....;`. This initializes the field and **you're done**... there's nothing to `@Autowire`. If you need to use the cache from multiple places, then you can let Spring manage the class containing it. – maaartinus Jan 07 '18 at 20:39