Şuayb's BlogŞuayb's Blog
Home
Categories
Games
MediumAboutContact
Language
Theme
    1. Blog
    2. Programming
    3. Spring Boot Redis Caching

Spring Boot Redis Caching

PublishedDecember 22, 2024
UpdatedDecember 23, 2024
Reading time3 min read
JavaKotlinSpring BootRedisCaching
XLinkedInFacebook
Spring Boot Redis Caching

Loading likes...

Redis is a powerful in-memory data store often used for caching, messaging, and real-time data management. This guide explains how to integrate Redis into a Spring Boot application using both Java and Kotlin.


Last updatedDecember 23, 2024

Total viewsLoading hits...

Previous articleSpring Boot with OpenAPINext articleSpring Boot Kafka Integration
Şuayb Şimşek

Written by

Şuayb Şimşek

Backend-focused fullstack developer sharing practical notes on Spring Boot, security, microservices, and cloud-native architecture.

Expertise

  • Spring Boot
  • Go
  • Microservices
  • Next.js
  • Cloud Native

Connect

GitHubLinkedInMedium

Related posts

Spring Boot Configuration Properties
Programming

Spring Boot Configuration Properties

Learn how to use @ConfigurationProperties for type-safe configuration, validate settings with @Validated, and manage environment-specific values with profile-specific application-{profile}.yml files.

February 4, 20263 min read
JavaKotlinSpring BootConfiguration
Spring Boot GraphQL JWE Authentication
Programming

Spring Boot GraphQL JWE Authentication

Learn how to secure your Spring Boot GraphQL APIs with stateless encrypted JWTs (JWE) while persisting user identities and roles in a JPA-backed database.

May 17, 20256 min read
JavaKotlinSpring BootSecurityJWTJWEGraphQL
Spring Boot JWE Authentication with JPA
Programming

Spring Boot JWE Authentication with JPA

Learn how to use stateless encrypted JWTs (JWE) to secure your Spring Boot APIs while persisting user identities and roles in a JPA-backed database.

May 11, 20254 min read
JavaKotlinSpring BootSecurityJWTJWEJPA

About

Articles on Spring Boot, microservices, security, and more.

ContactStart here

Latest posts

  • Captain Tsubasa 2: World Fighters
  • Captain Tsubasa: Rise of New Champions
  • Spring Boot Configuration Properties
  • Spring Boot GraphQL JWE Authentication
  • Spring Boot JWE Authentication with JPA

Top topics

JavaKotlinSpring BootJWEJWTMicroservice

Subscribe

Get practical backend + fullstack notes when new articles are published.

Social

© 2024-2026 Şuayb's Blog. All rights reserved.

🌟 Why Use Redis?

In this section, we clarify Why Use Redis? and summarize the key points you will apply in implementation.

  • High Performance: Redis provides extremely low latency for read and write operations.
  • Versatile Data Structures: Supports strings, hashes, lists, sets, and more.
  • Scalability: Ideal for distributed caching and real-time analytics.
  • Integration: Easily integrates with Spring Boot for seamless development.

📋 Prerequisites

🗈 Ensure you have the following:

  • ☕ Java Development Kit (JDK) 17+
  • 📦 Maven or Gradle installed
  • 🔤 A Java IDE (e.g., IntelliJ IDEA, Eclipse)
  • 💠 Redis Server installed and running locally or accessible via a network

🛠️ Step 1: Add Dependencies

To integrate Redis into your Spring Boot project, add the following dependencies:

  • Maven:
XMLpom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  • Gradle:
GROOVYbuild.gradle
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

🛠️ Step 2: Configure Redis

Set up the Redis connection in your application.properties or application.yml file.

Example Configuration:

Use this configuration as a baseline and adjust values for your local or production environment.

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

For advanced setups, such as password authentication or SSL, add these properties:

PROPERTIESapplication.properties
spring.redis.password=yourpassword
spring.redis.ssl=true

🛠️ Step 3: Enable Caching

Add the @EnableCaching annotation to your main application class to enable Spring's caching abstraction.


🛠️ Step 4: Service Layer Example with Caching


Configuring TTL (Time-To-Live)

Set the cache expiration time in your application.properties file:

PROPERTIESapplication.properties
spring.cache.redis.time-to-live=600000

This sets the TTL to 10 minutes (600,000 milliseconds).


Controller Example

Create a REST controller to expose the caching functionality.


▶️ Running the Application

Run the application using the following command:

BASH
./mvnw spring-boot:run

🧪 Testing the API

You can test the API using cURL or Postman:

  • Fetch a User (cached):
BASH
curl -X GET http://localhost:8080/users/1

🏁 Conclusion

You now have a practical Spring Boot Redis Caching implementation with a clear, production-friendly Spring Boot structure. As a next step, adapt configuration and tests to your own domain, then validate behavior under realistic traffic and failure scenarios.

JAVARedisApplication.java
package com.example.redis;

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

@SpringBootApplication
@EnableCaching
public class RedisApplication {
  public static void main(String[] args) {
    SpringApplication.run(RedisApplication.class, args);
  }
}
KOTLINRedisApplication.kt
package com.example.redis

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cache.annotation.EnableCaching

@SpringBootApplication
@EnableCaching
class RedisApplication

fun main(args: Array<String>) {
  runApplication<RedisApplication>(*args)
}
JAVAUserService.java
package com.example.redis.service;

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

@Service
public class UserService {

  @Cacheable("users")
  public String getUserById(String id) {
    simulateSlowService();
    return "User with ID: " + id;
  }

  private void simulateSlowService() {
    try {
      Thread.sleep(3000L);
    } catch (InterruptedException e) {
      throw new IllegalStateException(e);
    }
  }
}
KOTLINUserService.kt
package com.example.redis.service

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

@Service
class UserService {

  @Cacheable("users")
  fun getUserById(id: String): String {
    simulateSlowService()
    return "User with ID: $id"
  }

  private fun simulateSlowService() {
    Thread.sleep(3000L)
  }
}
JAVAUserController.java
package com.example.redis.controller;

import com.example.redis.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

  private final UserService userService;

  @GetMapping("/{id}")
  public String getUser(@PathVariable String id) {
    return userService.getUserById(id);
  }
}
KOTLINUserController.kt
package com.example.redis.controller

import com.example.redis.service.UserService
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/users")
class UserController(
  private val userService: UserService
) {
  @GetMapping("/{id}")
  fun getUser(@PathVariable id: String): String = userService.getUserById(id)
}