Databases 13 min read

Mastering Spring Data Redis: From Configuration to Advanced Queries

Learn how to integrate Spring Data Redis with Spring Boot, replace Jedis with Lettuce, define data models using @RedisHash and @Indexed, configure connection properties, implement CRUD and example queries, and understand the underlying key-value storage patterns illustrated with practical code and visual examples.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Mastering Spring Data Redis: From Configuration to Advanced Queries

Some developers still use Jedis directly to operate Redis, which is inconvenient and inflexible. Integrating Redis with Spring Boot allows convenient operations and the ability to switch between Lettuce and Jedis.

Jedis is being phased out; Lettuce is the default client in Spring Data Redis.

Spring Data Redis is a high‑level abstraction. It provides DAO implementations by extending CrudRepository, supports method‑name keyword queries (only on indexed fields), custom query methods via additional interfaces, and Example queries.

DAO interface only needs to extend CrudRepository; Spring Data Redis provides implementation.

Supports method‑name keyword queries; query attributes must be indexed.

Custom query methods can be added by defining extra interfaces and providing implementations, which are then “migrated” into the DAO.

Supports Example queries.

Method‑name keyword queries are less powerful than JPA because Redis is a simple key‑value store. Supported keywords include:

And – e.g., findByNameAndAge

Or – e.g., findByNameOrAge

Is / Equals – e.g., findByNameIs, findByName, findByNameEquals

Top / First – e.g., findFirst5ByName, findTop5ByName

Two annotations map a data class to Redis:

@RedisHash – maps the class to a Redis hash object.

@TimeToLive – applied to a numeric field to specify the object's TTL.

Two indexing annotations:

@Indexed – creates an index for a regular property, enabling queries.

@GeoIndexed – creates an index for Geo‑type properties.

To demonstrate Spring Data Redis, create a Maven project that inherits spring-boot-starter-parent and adds dependencies spring-boot-starter-data-redis, commons-pool2, and spring-boot-starter-test.

Define application.properties to configure Redis connection:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=1
spring.redis.password=32147
spring.redis.lettuce.pool.maxActive=20
spring.redis.lettuce.pool.maxIdle=20
spring.redis.lettuce.pool.minIdle=2

Define the data class:

@RedisHash("book")
public class Book {
    @Id
    private Integer id;
    @Indexed
    private String name;
    @Indexed
    private String description;
    private Double price;
    @TimeToLive(unit = TimeUnit.HOURS)
    private Long timeout;
    // getters, setters, constructors omitted
}

Define the DAO interface:

public interface BookDao extends CrudRepository<Book, Integer>,
                                   QueryByExampleExecutor<Book> {
    List<Book> findByName(String name);
    List<Book> findByDescription(String description);
}

Test class demonstrates CRUD and query operations:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class BookDaoTest {
    @Autowired
    private BookDao bookDao;

    @Test
    public void testSaveWithId() {
        var book = new Book("Crazy Python",
                "A clear Python book covering data analysis, crawling, etc.", 118.0);
        book.setId(2);
        book.setTimeout(5L);
        bookDao.save(book);
    }

    @Test
    public void testUpdate() {
        bookDao.findById(2).ifPresent(b -> {
            b.setName("Crazy Python Lecture");
            bookDao.save(b);
        });
    }

    @Test
    public void testDelete() {
        bookDao.deleteById(2);
    }

    @ParameterizedTest
    @CsvSource({"Crazy Java Lecture, The most comprehensive Java book, 129.0",
                "SpringBoot Ultimate Lecture, Unparalleled SpringBoot book, 119.0"})
    public void testSave(String name, String description, Double price) {
        var book = new Book(name, description, price);
        bookDao.save(book);
    }

    @ParameterizedTest
    @ValueSource(strings = {"Crazy Java Lecture"})
    public void testFindByName(String name) {
        bookDao.findByName(name).forEach(System.out::println);
    }

    @ParameterizedTest
    @ValueSource(strings = {"The most comprehensive Java book"})
    public void testFindByDescription(String description) {
        bookDao.findByDescription(description).forEach(System.out::println);
    }

    @ParameterizedTest
    @CsvSource({"Crazy Java Lecture, The most comprehensive Java book"})
    public void testExampleQuery1(String name, String description) {
        var probe = new Book(name, description, 1.0);
        bookDao.findAll(Example.of(probe)).forEach(System.out::println);
    }

    @ParameterizedTest
    @ValueSource(strings = {"SpringBoot Ultimate Lecture"})
    public void testExampleQuery2(String name) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnorePaths("description");
        var probe = new Book(name, "test", 1.0);
        bookDao.findAll(Example.of(probe, matcher)).forEach(System.out::println);
    }
}

Running the tests stores data in Redis. The following images illustrate the generated keys and their contents.

The book key stores a Set of all Book IDs. The book:id key stores a Hash with the full object data. Indexed properties such as name and description generate keys like book:name:Crazy Python that hold Sets of matching IDs, enabling fast look‑ups. The book:id:idx key stores additional auxiliary keys.

When querying an indexed property, Spring Data Redis retrieves the corresponding Set of IDs, then fetches each full object via its book:id hash, resulting in highly efficient read operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaredisSpring BootCRUDLettuceSpring Data Redis
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.