Cache Management with Redis in Spring

Ichwan Sholihin
Stackademic
Published in
5 min readFeb 25, 2024

--

Spring Redis

Hi good developers 👋️. In this article, I will discuss about cache management in Spring using Redis. Cache is one of the effective strategies to enhance application performance by storing frequently accessed data in a fast storage, allowing for quicker retrieval compared to fetching it from original source. In Java app development environment, especially when using the Spring framework, Redis is a popular choice as an external cache storage.

Redis is a high-performance key-value database that can be utilized as a cache storage in various apps. Redis stores data in memory, making data access faster. Spring Framework provides easy-to-use support for cache management, and by integrating it with Redis, we can improve application performance by leveraging caching features. By integrating Redis, you can take advantage of Redis features such as expiration time, distributed caching, and others. Additionally, Redis enables horizontal scalability, making it easy for your application to handle increased loads.

Installation Redis

In initial step, first install Redis according to operating system you are using. You can refer to and read Redis installation docs in here:

Setup Project in Spring

Create a Spring project on start.spring.io page and add some dependencies such as Spring Web, Lombok, and Spring Data Redis (Access + Driver).
To integrate Spring with Redis, there are several configurations in the application.properties file as shown in the following code:

For configuration with the prefixes spring.data.redis and spring.cache.redis, you can learn more in this documentation:

In the Spring configuration with spring.data.redis.client-type=lettuce, it refers to the use of Lettuce as the Redis client in the Spring project. Lettuce is one of the popular Redis clients and can be used to interact with the Redis server. Lettuce is designed to support a non-blocking model and can be used synchronously and asynchronously. By using Lettuce, Spring applications can take advantage of features such as multiple connections, better error handling, and better performance compared to other Redis clients.
Next, run the command redis-server in the terminal, and redis-cli -h localhost -p 6379 as the Redis client.

Entity Time to Live

Then create a product entity class with annotations from Lombok and Redis.

Entity TTL

@KeySpace annotation is used to determine the name of keyspace in which entity will be stored. In Redis, “keyspace” refers to a namespace that separates various types of data or entities. For example, you might have one keyspace to store product data and another keyspace to store customer data. When a product has an ID of 1, data in Redis will be stored with prefix “products:1.”

Meanwhile,@TimeToLive annotation is used to set expiration time of a piece of data, and its attribute must have a numerical value. This annotation will determine how long data will be retained in Redis before being automatically deleted.

Key Value Repository

First, add the @EnableRedisRepositories annotation to the SpringApplication class, then create a repository class that inherits from KeyValueRepository interface as follows.

Key Value Repository

KeyValueRepository is part of the Spring Data Redis framework that provides a common interface for CRUD (Create, Read, Update, Delete) operations on data in Redis. This interface allows developers to access and manage data in Redis without writing a lot of code manually.

Caching Services

Before implementing several Redis cache annotations, first add the @EnableCaching annotation to the main Spring class. The @Cacheable annotation in Spring is used to indicate that the result of the annotated method can be cached. When this method is called with the same parameters, the result will be retrieved from the cache instead of actually executing the method. This annotation indicates that the return value of the method should be stored in the cache.

By default, RedisCacheManager will also store data in binary form, so when creating the entity class initially, it should implement Serializable to be stored as binary data.

Cacheable

Annotation @CachePut in Spring is used to mark methods that will modify data in the cache. When this method is called, the generated value will be placed or updated in the cache with the corresponding key. If the cache does not exist, it will be created.

CachePut

The @CacheEvict annotation in Spring is used to remove data from the cache. When a method annotated with @CacheEvict is executed, data corresponding to specific parameters or conditions will be removed from the cache. If you are using Redis as the cache storage, you can combine @CacheEvict with Spring Data Redis configuration.

CacheEvict

The following is the implementation of unit tests for each cache that has been applied to the ProductService.java class.

ProductService Test

Using Redis as an external cache storage in Spring can significantly improve the performance of your application. By leveraging the cache management features provided by Spring and the fast caching capabilities of Redis, your application can deliver a more responsive experience to users. Make sure to configure caching settings and strategies according to your application’s needs to achieve optimal results.

Follow me on LinkedIn, Github, Dev.to, and Instagram.

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--