RedisTemplate
RedisTemplate is the central Spring API — opsForValue, opsForHash, opsForZSet wrap Redis commands with serialization hooks.
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.
flowchart LRController --> ServiceService --> RedisTemplateRedisTemplate --> Redis
Step-by-step explanation
- Template serializes key/value to bytes.
- Sends command via connection factory.
- Deserializes reply to Java type.
- Connection returned to pool.
- Exceptions wrapped in DataAccessException.
Syntax reference
Common commands
- Duration TTL overload on set.
- BoundKeyOperations for fixed key prefix.
- DefaultRedisSerializer is JDK — override.
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:
@Servicepublic 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?
Q2BeginnersetIfAbsent use?
Q3IntermediateFix ClassCastException on cache get?
Q4IntermediatePipeline in RedisTemplate?
Q5AdvancedMultiple templates in one app?
Summary
RedisTemplate = typed Redis command facade.