Redis Integration and Caching
Introduction
Redis stores key-value data in memory—session cache, rate limits, OTP codes, and shared counters across app instances. Spring Boot integrates Redis through spring-boot-starter-data-redis with Lettuce client. This chapter connects to Redis, uses RedisTemplate, applies @Cacheable, and notes distributed lock basics.
Prerequisites
- Spring Boot Startup Flow
- Redis running locally, Docker, or Linux Docker chapter
Run Redis (Docker)
docker run -d --name redis-learn -p 6379:6379 redis:7Verify:
docker exec -it redis-learn redis-cli pingExpected: PONG.
Add Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>Configure Connection
application.yml:
spring:
data:
redis:
host: localhost
port: 6379
password: ${REDIS_PASSWORD:}
timeout: 2sWith password:
spring:
data:
redis:
password: your_redis_passwordRedisTemplate Example
Code explanation:
StringRedisTemplatestores string keys/values—simplest startDurationsets TTL—key auto-expires
JSON Values With Generic RedisTemplate
Configure RedisTemplate<String, Object> with GenericJackson2JsonRedisSerializer for complex objects—mind class evolution and security (do not deserialize untrusted types).
Declarative Caching
Enable caching:
@SpringBootApplication
@EnableCaching
public class DemoApplication { }spring:
cache:
type: redis
redis:
time-to-live: 10mService:
Code explanation:
- First
getByIdhits DB; later calls read Redis until eviction/TTL @CacheEvictclears stale entry on update
Cache Key Design
| Pattern | Example key |
|---|---|
| Entity by id | users::42 |
| Query hash | search::md5(params) |
| Session | session:token |
Prefix keys by app/env: prod:users:42 in shared Redis clusters.
Distributed Lock (Concept)
For cron or checkout across nodes, use SET key value NX EX seconds pattern or libraries (Redisson, Spring Integration). Locks must have TTL to avoid deadlocks if JVM crashes.
Not a full lock tutorial—avoid homemade locks in critical finance without review.
Serialization and Charset
Store UTF-8 strings; binary for protobuf/JSON blobs. Keep values small—Redis is memory-bound.
FAQ
Connection refused?
Redis not running, wrong host/port, or Docker network mismatch.
Lettuce vs Jedis?
Boot defaults Lettuce—async-capable; Jedis optional.
Cache not working?
Missing @EnableCaching, wrong spring.cache.type, or self-invocation bypassing proxy.
Redis down—app crash?
Configure resilience or fallback; cache is often optional layer.
Cluster / Sentinel?
spring.data.redis.cluster.nodes or Sentinel config—production topology.
Memory eviction?
Set maxmemory-policy on Redis server—monitor keys with redis-cli INFO.