Enable Caching in Spring Boot
This post will discuss how to enable caching in Spring Boot.
Caching is a technique that improves the performance and scalability of a web application by storing frequently used data or results in memory or other storage systems. Caching can reduce the number of database queries, network calls, or computations that are needed to serve a request. Spring Boot provides a powerful and easy-to-use caching abstraction that supports various caching implementations and annotations.
There are several ways to enable caching in Spring Boot, depending on the desired caching provider and configuration. Here are some of the possible methods:
1. Using @EnableCaching Annotation
This is the simplest and most common way to enable caching in Spring Boot. The @EnableCaching annotation activates the Spring caching support and scans the application for any methods that are annotated with @Cacheable, @CachePut, @CacheEvict, or @Caching. These annotations allow us to specify which methods should be cached, how to update or invalidate the cache, and other cache-related settings. The following code illustrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Enable caching support @EnableCaching @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } // Define a service class with a cacheable method @Service public class BookService { // Cache the result of this method with the book id as the key @Cacheable(value = "books", key = "#id") public Book findBookById(Long id) { // Simulate a slow database query try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } // Return a book object return new Book(id, "Spring Boot Caching 101"); } } |
2. Using spring.cache.type Property
This is a way to configure the type of cache provider that Spring Boot should use. By default, Spring Boot will use a simple in-memory cache based on a ConcurrentMap. However, we can change this behavior by setting the spring.cache.type property in the application.properties file or as an environment variable. The possible values for this property are: none, simple, caffeine, ehcache, hazelcast, infinispan, jcache, couchbase, redis, or generic. For instance:
spring.cache.type=redis
# Configure the Redis connection properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=secret
3. Using Custom CacheManager Bean
This is a way to customize the cache provider and configuration programmatically. We can create a bean of type CacheManager in our configuration class and configure it with various properties and options. For example, we can use Caffeine as our cache provider and set the maximum size and expiration time for each cache. The following code illustrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Import the Caffeine library import com.github.benmanes.caffeine.cache.Caffeine; // Define a configuration class @Configuration public class CacheConfig { // Create a CacheManager bean with Caffeine @Bean public CacheManager cacheManager() { // Create a CaffeineSpec instance with the desired properties CaffeineSpec spec = CaffeineSpec.parse("maximumSize=100,expireAfterAccess=5m"); // Create a CaffeineCacheManager instance with the spec CaffeineCacheManager cacheManager = new CaffeineCacheManager(); cacheManager.setCaffeineSpec(spec); // Return the cache manager return cacheManager; } } |
That’s all about ways to enable caching in Spring Boot.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)