What is Spring Cache?

Spring is a lightweight, flexible application framework for the Java programming language. Dependency injection (i.e. “injecting” object dependencies into other objects) is a key concept of the Spring framework. However, the Spring ecosystem includes a wide range of tools and technologies that can help speed up and simplify the software development process.

One technique that can help improve the performance of your Java applications is using cache memory. With caching, information that is frequently used or recently used is saved in cache memory so that it can be accessed more quickly by the application. But can you perform caching in Spring? And what about using Spring caching with Redis?

Below, we’ll discuss everything you need to know: what the Spring cache is, how caching in Spring works, and more.

What is Spring caching?

Since the release of Spring version 3.1 in 2012, the Spring framework has included support for caching. More specifically, caching is part of Spring Boot, a component of the Spring ecosystem for rapid application development (RAD) and microservices. Spring caching must be enabled with the @EnableCaching annotation in Java.

How does Spring caching work?

In addition to the @EnableCaching annotation, below are some more Java annotations you need to know about to use caches in Spring:

  • @Cacheable: If a method is annotated with @Cacheable, then the results of this method will be placed in the Spring cache. Calling this method again with the same arguments will cause Spring to look up the results in the cache, instead of executing the method.
  • @CachePut: A method annotated with @CachePut will trigger a cache put operation. Unlike @Cacheable, @CachePut will always run the method when it is called and store the results in the Spring cache.
  • @CacheEvict: A method annotated with @CacheEvict will trigger a cache evict operation.
  • @CacheConfig: A class annotated with @CacheConfig will share its cache settings, such as cache name and key generator, with all the methods in the class.

Spring caching in Redis

Redis is an open-source in-memory data structure store widely used to implement NoSQL key-value databases, caches, and message brokers. According to the 2020 Stack Overflow developer survey, Redis remains the “most loved” database technology among users.

Unfortunately, Redis does not include support for either the Java programming language in general or Java application frameworks like Spring, out of the box. The good news is that you can use a third-party Redis Java client such as Redisson to implement a Spring cache.

When doing Spring caching in Redis with Redisson, there are two parameters for your cache eviction policy that you should be aware of:

  • ttl: The ttl parameter, which is short for “time to live”, controls how an object will “live” in the cache. Once this time limit is up, the object will be deleted from the cache, no matter how often it is requested.
  • maxIdleTime: The maxIdleTime parameter controls how much time can elapse between two different cache requests for the same object. For example if maxIdleTime is set to 10,000, then the object will be deleted once 10,000 milliseconds (10 seconds) have elapsed without a request for the object.

Note that in Redisson, both ttl and maxIdleTime are specified using milliseconds. If these parameters are set to 0 or undefined, then objects will live in the cache indefinitely.

With Redisson, you can use local caching to perform read operations up to 45 times faster. Below is some example code illustrating how to perform Spring caching in Redis. Note the use of the @EnableCaching annotation at the start of the code. We use two Spring beans in this code: one to create the Redisson client, and another to create the cache.

@Configuration
@ComponentScan
@EnableCaching
public class Application {

    @Bean(destroyMethod="shutdown")
    RedissonClient redisson() {
        Config config = new Config();
        config.useSingleServer()
              .setAddress("redis://127.0.0.1:6379");
        return Redisson.create(config);
    

    @Bean
    CacheManager cacheManager(RedissonClient redissonClient) {
        Map<String, CacheConfig> config = new HashMap<>();

        // create "testMap" spring cache with ttl = 24 minutes and maxIdleTime = 12 minutes
        config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
        return new RedissonSpringCacheManager(redissonClient, config);
    }

}
Similar terms