zakpruitt
zakpruitt

Reputation: 322

Caffeine cache application.properties config vs CacheManager class config

I am currently learning caffeine and I am new to Spring in general. I've been trying to implement caching with caffeine; however, I find myself running into a few questions.

I have seen two ways to configure the caffeine cache.

First is with a Java class:

public class CaffeineCacheConfig {
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeieneCacheManager("example");
        cacheManager.setCaffeiene(caffeieneCacheBuilder());
        return cacheManager;

    Caffeiene<Object, Object> caffeieneCacheBuilder() {
        return Caffeine.newBuilder()
            .initialCapactiy(100)
            .maximumSize(500)
            .expireAfterAccess(10, TimeUnit.MINUTES)
            .recordStats()
    }
}

Second is within application.proprerties:

spring.cache.type=caffeine
spring.cache.cache-names=books
spring.cache.caffeine.spec=expireAfterAccess=60s

I wanted to ask if there is anything differentation from these two? Do I need both a class and application.properties configurations, or just 1 of them? Further, within the Java class implementation, would the cacheManager only apply to caches with the name "example" or would it be applied to every cache?

Thanks so much!

Upvotes: 1

Views: 6951

Answers (1)

Santiago Medina
Santiago Medina

Reputation: 579

Properties is easier to start with because you just put the cache names and parameters and then provide a cache implementation (Caffeine) as a dependency, and it works without additional Java code.

The main advantage of using a configuration class instead of properties, is that you can have different parameters for different caches (sometimes you want different ttl, or maximum size for different entities, or you want some of them to never expire, etc).

In this answer I posted an example of how to do that with Spring Boot: Define multiple caches configurations with Spring and Caffeine

Upvotes: 2

Related Questions