Spring-Boot 4 min read

Introduction to Spring Data Redis

Learn how to integrate Redis with Spring Boot using Spring Data Redis. Complete guide with Docker setup and practical examples.

MR

Moshiour Rahman

Advertisement

Overview

This article is an introduction to Spring Data Redis, which provides the abstractions of the Spring Data platform to Redis - the popular in-memory data structure store. Redis is driven by a keystore-based data structure and can be used as a database, cache, or message broker.

Creating The Project

Let’s create a project using Spring Boot CLI. If you’re not familiar with spring-cli, it’s a handy tool for bootstrapping Spring applications.

You can install it from the official documentation.

Run the following command in your terminal:

spring init --dependencies=lombok,data-redis,web \
  --package=com.techyowls \
  --build=gradle \
  spring-data-redis

Alternatively, use Spring Initializr:

  1. Go to start.spring.io
  2. Select Gradle Project and Java
  3. Enter Artifact as spring-data-redis
  4. Add dependencies: Spring Web, Spring Data Redis, and Lombok
  5. Click Generate to download the project

Running Redis with Docker Compose

We’ll run a Redis standalone instance locally using docker-compose:

version: '3.8'
services:
  redis:
    image: redis:7-alpine
    container_name: redis
    networks:
      - redis-net
    ports:
      - "6379:6379"
    command: redis-server --appendonly yes
    volumes:
      - redis-data:/data
    restart: always

networks:
  redis-net:

volumes:
  redis-data:

Start the Redis server:

docker-compose up -d

Redis Configuration

To establish the connection between your application and the Redis server, you need a Redis client. We’ll use Lettuce, which is included with spring-boot-starter-data-redis.

build.gradle

plugins {
    id 'org.springframework.boot' version '3.2.0'
    id 'io.spring.dependency-management' version '1.1.4'
    id 'java'
}

group = 'com.techyowls'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

Redis Configuration Class

@Configuration
@EnableRedisRepositories
public class RedisConfiguration {

    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

Key annotations:

  • @Configuration - Marks this as a Spring configuration class
  • @EnableRedisRepositories - Activates Redis repositories

Custom Connection Properties

For custom configuration, modify the LettuceConnectionFactory:

@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
    config.setHostName("localhost");
    config.setPort(6379);
    // config.setPassword("your-password"); // If needed
    return new LettuceConnectionFactory(config);
}

Or use application.yml:

spring:
  data:
    redis:
      host: localhost
      port: 6379
      # password: your-password

Entity

Create a User entity for our example:

@RedisHash("user")
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
public class User {

    @Id
    private Long id;

    @Indexed
    private String firstName;

    private String lastName;

    private Integer age;
}

Key annotations:

  • @RedisHash("user") - Marks this as a Redis hash with the prefix “user”
  • @Id - The unique identifier for the entity
  • @Indexed - Enables querying by this field (otherwise, only key-based queries work)

Note: If you’re not familiar with Lombok, check out my Lombok tutorial.

Repository

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
    List<User> findByFirstName(String firstName);
}

Spring Data Redis creates an abstraction layer, hiding the complexity of how Redis stores data. The findByFirstName method works just like Spring Data JPA!

REST Controller

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

    private final UserRepository userRepository;

    @PostMapping
    public ResponseEntity<User> createUser(@Valid @RequestBody User request) {
        User savedUser = userRepository.save(request);
        URI location = ServletUriComponentsBuilder
            .fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(savedUser.getId())
            .toUri();
        return ResponseEntity.created(location).body(savedUser);
    }

    @GetMapping
    public ResponseEntity<Iterable<User>> getAllUsers() {
        return ResponseEntity.ok(userRepository.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userRepository.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/search")
    public ResponseEntity<List<User>> findByFirstName(
            @RequestParam String firstName) {
        return ResponseEntity.ok(userRepository.findByFirstName(firstName));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}

Testing the API

Create a User

curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"firstName": "Moshiour", "lastName": "Rahman", "age": 30}'

Response:

{
  "id": 2038251604388001320,
  "firstName": "Moshiour",
  "lastName": "Rahman",
  "age": 30
}

Get All Users

curl http://localhost:8080/api/users

Search by First Name

curl "http://localhost:8080/api/users/search?firstName=Moshiour"

Response:

[
  {"id": 2038251604388001320, "firstName": "Moshiour", "lastName": "Rahman", "age": 30},
  {"id": 2353021852542279850, "firstName": "Moshiour", "lastName": "Ahmed", "age": 25}
]

Conclusion

This article provided a clear introduction to implementing Spring Data Redis with Spring Boot. We covered:

  • Setting up Redis with Docker Compose
  • Configuring the Redis connection
  • Creating entities and repositories
  • Building a REST API for CRUD operations

In future posts, we’ll explore more advanced use cases like caching and pub/sub messaging.

Source Code: GitHub Repository

Advertisement

MR

Moshiour Rahman

Software Architect & AI Engineer

Share:
MR

Moshiour Rahman

Software Architect & AI Engineer

Enterprise software architect with deep expertise in financial systems, distributed architecture, and AI-powered applications. Building large-scale systems at Fortune 500 companies. Specializing in LLM orchestration, multi-agent systems, and cloud-native solutions. I share battle-tested patterns from real enterprise projects.

Related Articles

Comments

Comments are powered by GitHub Discussions.

Configure Giscus at giscus.app to enable comments.