Caching is a powerful technique to improve the performance of applications by storing frequently accessed data in a fast-access storage area.
In a Spring Boot application, the integration of caching is seamless, thanks to the support provided by the Spring Framework.
In This Article we choose the caffeine cache Manager to configure our cache.
The particularity about this article, is the cache configuration when we have more than one
entry in the cacheManager.
Configuring Caches for different entries with Caffeine
In this example, I’ll explore how to configure and use caching in a Spring Boot application using the Caffeine cache implementation.
Caffeine is a high-performance, near-optimal caching library for Java.
Cache Configuration Class
Let’s start by creating a configuration class that defines our caching strategy.
The class CacheConfig is responsible for setting up two caches: client_token and server_token. Here’s the configuration:
@Configuration
@ConfigurationProperties(prefix = "cache")
@Profile("!test")
@Getter
@Setter
public class CacheConfig {
@Getter
@Setter
public static class CacheSpec {
private Integer expireAfterWriteInMinutes = 75;
private Integer maximumSize = 10000;
}
private Map<String, CacheSpec> specs;
@Bean
@Primary
public CacheManager simpleCacheManager() {
SimpleCacheManager manager = new SimpleCacheManager();
if (specs != null) {
manager.setCaches(
specs.entrySet()
.stream()
.map(entry -> buildCache(entry.getKey(), entry.getValue()))
.toList()
);
}
return manager;
}
private CaffeineCache buildCache(String name, CacheSpec cacheSpec) {
return new CaffeineCache(name, Caffeine.newBuilder()
.expireAfterWrite(cacheSpec.getExpireAfterWriteInMinutes(), TimeUnit.MINUTES)
.maximumSize(cacheSpec.getMaximumSize())
.build());
}
}
In this configuration class, we define a CacheSpec class to encapsulate cache-specific settings such as the expiration time and maximum size.
The CacheConfig class itself is annotated with @ConfigurationProperties to allow external configuration of cache properties.
Which I put in our configuration file yaml : application.yml
Cache Configuration yml properties
cache:
specs:
client_token:
expireAfterWriteInMinutes: 60
maximumSize: 50000
server_token:
expireAfterWriteInMinutes: 80
maximumSize: 50000
Here, the cache section includes specifications for the client_token and server_token caches.
You can easily customize the expiration time and maximum size according to your application’s requirements.
Using the Custom Annotation
Now, let’s use our custom annotation in a class:
import jakarta.validation.constraints.NotNull;
public class Vehicle {
@NotNull(message = "Type cannot be null")
@AllowedValues(allowedValues = {"Car", "Bicycle", "Truck"})
private String type;
}
Using Caching in a Service
Now, let’s see how we can use caching in a service.
The class ClientService demonstrates the usage of caching with the @Cacheable annotation for the getToken method:
@Service
@RequiredArgsConstructor
public class ClientService {
@Cacheable(value = "client_token", unless = "#result == null")
public String getToken() {
return client.getToken();
}
}
The @Cacheable annotation is used to specify that the return value of the getToken method should be cached.
The value attribute specifies the name of the cache (in this case, “client_token”),
and the unless attribute ensures that null results are not cached.
Conclusion
By integrating caching into your Spring Boot application,
you can significantly improve performance by reducing the load on external services and optimizing the response time of critical operations.
Leveraging tools like Caffeine and Spring’s caching annotations simplifies the implementation,
making it easier to achieve a performant and responsive application.
Ajouter un commentaire
Commentaires