Redis with Spring Boot

Harry · 13 Sep 2026 · 1 views

Dependencies

implementation 'org.springframework.boot:spring-boot-starter-data-redis'

Spring Data Redis supplies RedisTemplate, repositories and cache support.

Configuration

spring.data.redis.host=localhost
spring.data.redis.port=6379

Use RedisTemplate

@Service
public class SessionCache {
    private final StringRedisTemplate redis;

    public void put(String key, String value) {
        redis.opsForValue().set(key, value, Duration.ofMinutes(30));
    }

    public String get(String key) {
        return redis.opsForValue().get(key);
    }
}

StringRedisTemplate serializes strings easily; RedisTemplate with a JSON serializer handles objects.

Cache with @Cacheable

@Cacheable(value = "products", key = "#id")
public Product findById(Long id) { return repo.findById(id).orElse(null); }

With CacheManager backed by Redis, annotated methods populate the cache automatically and @CacheEvict invalidates on writes.

Key Points

  • Starter + properties enable Redis in seconds.
  • RedisTemplate exposes all data types.
  • @Cacheable/Evict declaratively cache methods.
  • TTL keys keep memory bounded.
Share this post:

Comments (0)

Please login or register to comment.