Hackforge Academy

Category: java

Introduction to Redis Caching

Published on 24 Jul 2026

Explanation

Redis is an in-memory data store used to cache frequently accessed data. Spring Boot integrates Redis with Spring Cache to reduce database queries, improve response times, and increase application performance for read-heavy workloads.

Code:

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

Explanation

Spring Cache provides a simple abstraction for caching method results. Enable caching by adding the @EnableCaching annotation to the main Spring Boot application. Spring automatically manages cache creation and retrieval.

Code:

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

Explanation

The @Cacheable annotation stores the result of a method in Redis. On subsequent calls with the same parameters, Spring returns the cached result instead of executing the method again, reducing database access.

Code:

@Cacheable(value = "students", key = "#id")
public Student getStudent(Long id) {
    return repository.findById(id).orElse(null);
}

Explanation

Use @CachePut to update cache entries after modifying data and @CacheEvict to remove outdated entries. This ensures the cache stays synchronized with the database and prevents stale data from being returned.

Code:

@CachePut(value = "students", key = "#student.id")
public Student updateStudent(Student student) {
    return repository.save(student);
}

@CacheEvict(value = "students", key = "#id")
public void deleteStudent(Long id) {
    repository.deleteById(id);
}

Explanation

Configure the Redis server in application.properties by specifying the host and port. Spring Boot automatically creates the Redis connection, allowing the application to use Redis as the cache provider with minimal configuration.

Code:

spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.cache.type=redis

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community