How to implement caching in Spring Boot using Redis

Caching improves application performance by storing frequently accessed data in memory, reducing database queries and response times. Redis, an in-memory data store, is a popular choice for caching in Spring Boot applications.

1. Add Dependencies

First, include the necessary dependencies in your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2. Configure Redis in Spring Boot

Add Redis configuration in application.properties or application.yml:

spring.redis.host=localhost
spring.redis.port=6379

If Redis requires authentication, add:

spring.redis.password=yourpassword

3. Enable Caching in Spring Boot

Add the @EnableCaching annotation in the main application class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class RedisCachingApplication {
    public static void main(String[] args) {
        SpringApplication.run(RedisCachingApplication.class, args);
    }
}

4. Create a Redis Cache Configuration (Optional)

If you need a custom configuration, create a Redis configuration class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class RedisConfig {
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        return template;
    }
}

5. Implement Caching in a Service

Use @Cacheable, @CachePut, and @CacheEvict annotations to manage caching.

5.1 Use @Cacheable to Store Data in Redis

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
        System.out.println("Fetching user from database...");
        return findUserById(id);
    }

    private User findUserById(Long id) {
        return new User(id, "John Doe");
    }
}

5.2 Use @CachePut to Update Cache

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    return saveUserToDatabase(user);
}

5.3 Use @CacheEvict to Remove Data from Cache

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
    deleteUserFromDatabase(id);
}

6. Testing Redis Caching

Start a Redis server using Docker:

docker run --name redis -p 6379:6379 -d redis

Then, call the service multiple times to observe caching behavior. The first call retrieves data from the database, while subsequent calls return cached data.

7. Monitor Redis Cache

Use the Redis CLI to check cached data:

redis-cli
keys *
get users::1

Conclusion

Using Redis with Spring Boot caching enhances application performance by reducing redundant database queries. Implement @Cacheable, @CachePut, and @CacheEvict to manage cache effectively.

Related post

Leave a Reply

Your email address will not be published. Required fields are marked *