Redis Tutorial 0/42 lessons ~6 min read Lesson 32

    RedisTemplate

    RedisTemplate is the central Spring API — opsForValue, opsForHash, opsForZSet wrap Redis commands with serialization hooks.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    RedisTemplate is the central Spring API — opsForValue, opsForHash, opsForZSet wrap Redis commands with serialization hooks. Every production bug from garbled cache values traces to serializer mismatch between writer and reader services.

    Operations are synchronous by default on Lettuce; use RedisCallback for low-level access. executeSession for WATCH/MULTI transactions.

    Namespace templates by domain bean — productRedisTemplate vs sessionRedisTemplate — to enforce serializer boundaries.

    Understanding the topic

    Key concepts

    • opsForValue() — string commands.
    • opsForHash() — hash commands.
    • opsForZSet(), opsForList(), opsForSet().
    • opsForStream() — stream commands Redis 5+.
    • Serializers on key, value, hash field.
    • execute(RedisCallback) low-level.
    text
    flowchart LR
    Controller --> Service
    Service --> RedisTemplate
    RedisTemplate --> Redis

    Step-by-step explanation

    1. Template serializes key/value to bytes.
    2. Sends command via connection factory.
    3. Deserializes reply to Java type.
    4. Connection returned to pool.
    5. Exceptions wrapped in DataAccessException.

    Syntax reference

    Common commands

    • Duration TTL overload on set.
    • BoundKeyOperations for fixed key prefix.
    • DefaultRedisSerializer is JDK — override.
    bash
    redis.opsForValue().set("k", "v", Duration.ofMinutes(10));
    redis.opsForHash().put("h", "field", "val");
    redis.opsForZSet().add("z", "member", 1.0);
    redis.delete("k");

    Informative example

    Domain-specific template with JSON values and key prefix helper:

    java
    @Service
    public class CatalogCache {
    private final RedisTemplate<String, Product> redis;
    public CatalogCache(RedisTemplate<String, Product> redis) { this.redis = redis; }
    public void put(String sku, Product p) {
    redis.opsForValue().set("catalog:" + sku, p, Duration.ofHours(1));
    }
    public Optional<Product> get(String sku) {
    return Optional.ofNullable(redis.opsForValue().get("catalog:" + sku));
    }
    }

    Java 21 · Spring Boot 3 · inject typed template bean from RedisConfig.

    Real-world use

    Real-world use cases

    • Cache CRUD in service layer.
    • Session hash via opsForHash.
    • Leaderboard via opsForZSet.
    • Distributed lock via opsForValue setIfAbsent.
    • Stream consumer via opsForStream.

    Best practices

    • Dedicated template beans per value type.
    • StringRedisTemplate for plain JSON strings.
    • Consistent key prefix constants class.
    • Use Duration TTL overloads not raw seconds.
    • executePipelined for batch paths.
    • Log serializer config at startup in debug.

    Common mistakes

    • Service A writes JSON string Service B reads with JDK serializer.
    • Sharing one template with mixed value types.
    • Ignoring null returns from get.
    • Blocking opsForStream in HTTP thread without timeout.

    Advanced interview questions

    Q1BeginneropsForValue maps to?
    Redis string commands SET GET INCR.
    Q2BeginnersetIfAbsent use?
    Distributed lock acquire SET NX.
    Q3IntermediateFix ClassCastException on cache get?
    Align value serializer across services; prefer JSON String or shared DTO serializer.
    Q4IntermediatePipeline in RedisTemplate?
    executePipelined with RedisCallback batch.
    Q5AdvancedMultiple templates in one app?
    Yes — per domain serializers and types; document key ownership.

    Summary

    RedisTemplate = typed Redis command facade.

    Ready to mark this lesson complete?Track your journey across the entire course.