Caches that outlive a restart

spring.cache.type: disk keeps every entry on disk, so a result survives a restart of the app: an API answer a phone asked for yesterday is there at the next start, without the network.

Why

The in-memory caches are empty after every start. On a phone that is every time the user opens the app, and on the web every time the page loads: the same answers are asked for again. A store on disk keeps them; it answers later than memory, so its caches are for methods that return a Future.

Example

spring:
  cache:
    type: disk                # simple: memory; disk: kept across restarts
    disk:
      time-to-live: 1h        # by the wall clock: it outlives a restart
      max-size: 50MB          # per cache; the oldest written go first
      version: 2.1.0          # an entry of another version is not read
      caches:
        profiles: { time-to-live: 10m }
@Component()
class Profiles {
  Profiles(this.api);
  final PassportApi api;

  @Cacheable('profiles')
  Future<Profile> find(String steamId) => api.profile(steamId);
}

How it works

@Configuration()
class CacheConfig {
  @Bean()
  @Primary()
  CacheManager memory() => InMemoryCacheManager(
        defaultSpec: const CacheSpec(timeToLive: Duration(minutes: 1)),
      );

  @Bean()
  CacheManager disk(CacheStore store, ObjectMapper mapper,
          Introspector introspector) =>
      DiskCacheManager(store: store, mapper: mapper,
          introspector: introspector, timeToLive: const Duration(days: 1));

  @Bean()
  CacheManager layered(CacheManager memory, CacheManager disk) =>
      LayeredCacheManager([memory, disk]);
}

Properties

Key Default Meaning
spring.cache.type simple disk keeps the entries on disk
spring.cache.disk.time-to-live none How long an entry lives, by the wall clock
spring.cache.disk.caches.<name>.time-to-live the global one The same, for one cache
spring.cache.disk.max-size none The most bytes each cache keeps
spring.cache.disk.directory .spring/cache The folder where no CacheStore bean gives a place
spring.cache.disk.version none The version entries are written by and read for
spring.cache.resource-version false A resource as a key by its content's version