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

Run Redis (Docker)

bash
docker run -d --name redis-learn -p 6379:6379 redis:7

Verify:

bash
docker exec -it redis-learn redis-cli ping

Expected: PONG.

Add Dependency

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Configure Connection

application.yml:

yaml
spring:
  data:
    redis:
      host: localhost
      port: 6379
      password: ${REDIS_PASSWORD:}
      timeout: 2s

With password:

yaml
spring:
  data:
    redis:
      password: your_redis_password

RedisTemplate Example

Code explanation:

  • StringRedisTemplate stores string keys/values—simplest start
  • Duration sets 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:

java
@SpringBootApplication
@EnableCaching
public class DemoApplication { }
yaml
spring:
  cache:
    type: redis
    redis:
      time-to-live: 10m

Service:

Code explanation:

  • First getById hits DB; later calls read Redis until eviction/TTL
  • @CacheEvict clears stale entry on update

Cache Key Design

PatternExample key
Entity by idusers::42
Query hashsearch::md5(params)
Sessionsession: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.