Mastering Redis Caching in Spring Boot: A Complete Beginner's Guide



Have you ever wondered how high-performance applications deliver results so quickly? One of the secrets is caching! In this blog, we'll explore Redis caching in Spring Boot, how to configure it, and use it effectively with annotations like @Cacheable.

Architecture Overview


Here's a high-level view of how Redis fits into a typical Spring Boot application:


Redis and Spring Boot Setup


Add dependency in pom.xml:


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

Configure application.yml:


spring:
  cache:
    type: redis
  redis:
    host: localhost
    port: 6379

Using @Cacheable for Caching


@Cacheable(cacheNames = "employees", key = "#id")
public Employee getEmployeeById(Long id) {
    return employeeRepository.findById(id).orElseThrow(...);
}

Explanation:

  • First time: Queries DB, stores result in Redis.
  • Next time: Fetches from Redis without querying DB.

Flow of @Cacheable




Using @CachePut for Caching


Unlike @Cacheable, @CachePut always executes the method and updates the cache with the result. It is useful when you want to refresh or update the cache every time a method is called, without skipping execution.

@CachePut(cacheNames = "employees", key = "#employee.id") public Employee updateEmployee(Employee employee) { return employeeRepository.save(employee); // Update DB and refresh cache }

Explanation:

  • Updates DB and puts/updates the latest result in cache.
  • Used in update operations where cache needs to stay fresh.

Conclusion


In this post, we covered the basics of Redis caching in Spring Boot. In the next blog, we will dive deeper into advanced caching, TTL, and cache invalidation. Stay tunned for the next blog.

Post a Comment

0 Comments