Skip to main content

Spring

added in: Xanthic v0.3.0

Description

This module provides a integration between Spring's Cache Abstraction and Xanthic. It provides a CacheManager implementation to delegate Spring's caching to your preferred Xanthic cache implementation.

Installation

build.gradle
dependencies {
implementation 'io.github.xanthic.cache:cache-spring-java17'
}
For SpringBoot 2.x / Spring 5.x, use this dependency instead
build.gradle
dependencies {
implementation 'io.github.xanthic.cache:cache-spring'
}

Usage

Configure a CacheManager bean with Xanthic's XanthicSpringCacheManager implementation.

The XanthicSpringCacheManager supports the following modes of operation:

  • Dynamic: Caches are created on demand with the default configuration or can be registered manually.
  • Static: The manually provided cache names are registered on startup and no further caches can be registered.

Dynamic

Configure the XanthicSpringCacheManager

@Configuration
@EnableCaching
public class CachingConfig {

@Bean
public CacheManager cacheManager() {
XanthicSpringCacheManager cacheManager = new XanthicSpringCacheManager(spec -> {
spec.maxSize(1000L); // customize the settings according to your needs
});
// you can create caches with custom settings manually, e.g.:
cacheManager.registerCache("my-custom-cache", spec -> {
spec.maxSize(5000L);
});
return cacheManager;
}
}

Manually create a Cache

The following snippet shows how to manually create a cache with custom settings:

@Autowired
private XanthicSpringCacheManager cacheManager;

public void myFunction() {
cacheManager.registerCache("small-cache", spec -> {
spec.maxSize(10L);
spec.expiryType(ExpiryType.POST_ACCESS);
spec.expiryTime(Duration.ofSeconds(10));
});
}

Dynamic Creation

If you refer to a non-existing cache name from the Spring Cache Abstraction, for example the @Cacheable annotation, the XanthicSpringCacheManager will create a new cache with the default settings provided in the spec.

@Cacheable("customer-cache")
public Customer getCustomerById(Long id) {
// ...
}

For more information about the Spring Cache Abstraction, please refer to the following resources:

Static

Configure the XanthicSpringCacheManager with explicit cache names

@Configuration
@EnableCaching
public class CachingConfig {

@Bean
public CacheManager cacheManager() {
XanthicSpringCacheManager cacheManager = new XanthicSpringCacheManager(spec -> {
spec.expiryType(ExpiryType.POST_ACCESS);
spec.expiryTime(Duration.ofSeconds(15));
spec.maxSize(10L);
}, Set.of("my-cache-name"));
return cacheManager;
}
}

The list of cache names provided in the constructor needs to be exhaustive within static mode, as no further caches can be registered at runtime.