DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Choosing the Right Caching Strategy
  • How to Connect Redis Sentinel With Spring
  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI
  • Caching Issues With the Spring Expression Language

Trending

  • How Performance Engineers Find and Fix Hidden System Bottlenecks
  • How to Keep AI Agents From Going Rogue Using Docker Sandbox
  • 9 Practical Ways to Fix Laravel Performance Issues in Production
  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Quick Start: How to Use Spring Cache on Redis

Quick Start: How to Use Spring Cache on Redis

Is your Spring app running? Well, you better go cache it!

By 
Nikita Koksharov
·
Updated Nov. 29, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
40.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Dog catching tennis ball in field

Is your Spring app running? Well, you better go cache it!

Spring is a highly popular application framework for the Java programming language that makes it easier to build enterprise Java software. Since version 3.1, Spring has supported adding caching to existing Spring applications, in order to improve performance and decrease response times.

Redis is an open-source, in-memory data structure store that can be used to build NoSQL databases. However, Redis does not include pre-built support for either Java in general or application frameworks such as Spring.

You may also like: How to Boost Redis With Local Caching in Java

The good news is that you can perform caching with Spring and Redis by using a third-party Redis Java client, such as Redisson. Redisson is fully compatible with the Spring framework. In this article, we’ll discuss how you can use Redisson to perform caching in Spring with Redis.

Caching in Spring

The Spring framework provides a caching abstraction layer. The relevant annotations for caching in Spring are as follows:

  • @Cacheable: The @Cacheable annotation denotes that the results of invoking this method will be cached. If the method is called again with the same arguments, the results will be retrieved from the cache instead of invoking the method.

  • @CachePut: The @CachePut annotation denotes that a method will trigger the cache put operation.

  • @CacheEvict: The @CacheEvict annotation denotes that a method will trigger the cache evict operation.

  • @EnableCaching: The @EnableCaching annotation enables Spring’s built-in cache management capabilities.

  • @Caching: The @Caching annotation is a group annotation for multiple cache annotations.

  • @CacheConfig: The @CacheConfig annotation enables the sharing of common cache-related settings, such as cache name and key generator.

Installing Redisson

Installing Redisson is very simple. If you are using Maven, for example, simply add the below dependency to your pom.xml file:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.11.5</version>
</dependency>


Caching Parameters in Redisson

Each Spring cache in Redisson has two important parameters, which are specified in milliseconds:

  • ttl: The ttl (time to live) parameter determines the maximum lifetime of an object in the cache. All objects in the cache will be deleted after their time to live has expired, no matter how frequently they are requested.

  • maxIdleTime: The maxIdleTime parameter determines the maximum time that can elapse between requests for an object. If this time goes by without a request, the object is automatically deleted from the cache. This parameter is present only in the Redisson implementation of Spring caching.

If these two parameters are not defined or equal to 0, then objects in the cache will be stored indefinitely.

Example Code for Caching With Spring and Redis

The example code below demonstrates how to perform caching in Spring and Redis with Redisson. This code makes use of two Spring beans: the first to create and configure the Redisson client, and the second to set up and test 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);
    }

}


Conclusion

Thanks to the power of local caching, Redisson allows you to boost the performance of your Redis-based Spring cache by up to 45 times for read operations.

Further Reading

How to Boost Redis With Local Caching in Java

Redis Cluster on Java for Scaling and High Availability

Spring Framework Cache (computing) Redis (company) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Choosing the Right Caching Strategy
  • How to Connect Redis Sentinel With Spring
  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI
  • Caching Issues With the Spring Expression Language

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook