$npx -y skills add rrezartprebreza/spring-boot-skills --skill spring-data-redisUse when implementing caching, session storage, rate limiting, or any Redis integration. Covers cache-aside pattern, key naming, TTL strategy, and serialization config.
| 1 | # Spring Data Redis |
| 2 | |
| 3 | ## Dependencies |
| 4 | |
| 5 | ```xml |
| 6 | <dependency> |
| 7 | <groupId>org.springframework.boot</groupId> |
| 8 | <artifactId>spring-boot-starter-data-redis</artifactId> |
| 9 | </dependency> |
| 10 | <dependency> |
| 11 | <groupId>org.springframework.boot</groupId> |
| 12 | <artifactId>spring-boot-starter-cache</artifactId> |
| 13 | </dependency> |
| 14 | ``` |
| 15 | |
| 16 | ## Configuration |
| 17 | |
| 18 | ```java |
| 19 | @Configuration |
| 20 | @EnableCaching |
| 21 | public class RedisConfig { |
| 22 | |
| 23 | @Bean |
| 24 | public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { |
| 25 | RedisTemplate<String, Object> template = new RedisTemplate<>(); |
| 26 | template.setConnectionFactory(factory); |
| 27 | template.setKeySerializer(new StringRedisSerializer()); |
| 28 | template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // JSON, not Java serialize |
| 29 | template.setHashKeySerializer(new StringRedisSerializer()); |
| 30 | template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); |
| 31 | return template; |
| 32 | } |
| 33 | |
| 34 | @Bean |
| 35 | public RedisCacheManager cacheManager(RedisConnectionFactory factory) { |
| 36 | RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() |
| 37 | .entryTtl(Duration.ofMinutes(10)) |
| 38 | .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) |
| 39 | .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) |
| 40 | .disableCachingNullValues(); |
| 41 | |
| 42 | return RedisCacheManager.builder(factory) |
| 43 | .cacheDefaults(config) |
| 44 | .withCacheConfiguration("orders", config.entryTtl(Duration.ofMinutes(5))) |
| 45 | .withCacheConfiguration("products", config.entryTtl(Duration.ofHours(1))) |
| 46 | .build(); |
| 47 | } |
| 48 | } |
| 49 | ``` |
| 50 | |
| 51 | ## Key Naming Convention |
| 52 | |
| 53 | ``` |
| 54 | {app}:{domain}:{id} → orders:order:uuid-here |
| 55 | {app}:{domain}:list:{filter} → orders:order:list:status:PENDING |
| 56 | {app}:session:{userId} → orders:session:uuid-here |
| 57 | {app}:ratelimit:{ip} → orders:ratelimit:192.168.1.1 |
| 58 | ``` |
| 59 | |
| 60 | ## @Cacheable — Declarative Caching |
| 61 | |
| 62 | ```java |
| 63 | @Service |
| 64 | @RequiredArgsConstructor |
| 65 | public class ProductService { |
| 66 | |
| 67 | @Cacheable(value = "products", key = "#id") |
| 68 | public ProductResponse findById(UUID id) { |
| 69 | return productRepository.findById(id) |
| 70 | .map(ProductResponse::from) |
| 71 | .orElseThrow(() -> new EntityNotFoundException("Product not found: " + id)); |
| 72 | } |
| 73 | |
| 74 | @CachePut(value = "products", key = "#result.id") // update cache after write |
| 75 | @Transactional |
| 76 | public ProductResponse update(UUID id, UpdateProductRequest request) { |
| 77 | Product product = productRepository.findById(id).orElseThrow(); |
| 78 | product.update(request); |
| 79 | return ProductResponse.from(productRepository.save(product)); |
| 80 | } |
| 81 | |
| 82 | @CacheEvict(value = "products", key = "#id") // invalidate on delete |
| 83 | @Transactional |
| 84 | public void delete(UUID id) { |
| 85 | productRepository.deleteById(id); |
| 86 | } |
| 87 | |
| 88 | @CacheEvict(value = "products", allEntries = true) // clear all |
| 89 | public void clearCache() {} |
| 90 | } |
| 91 | ``` |
| 92 | |
| 93 | ## Manual Cache-Aside Pattern |
| 94 | |
| 95 | ```java |
| 96 | @Service |
| 97 | @RequiredArgsConstructor |
| 98 | public class OrderCacheService { |
| 99 | |
| 100 | private final RedisTemplate<String, Object> redisTemplate; |
| 101 | private final ObjectMapper objectMapper; |
| 102 | private static final Duration TTL = Duration.ofMinutes(5); |
| 103 | |
| 104 | public Optional<OrderResponse> get(UUID orderId) { |
| 105 | String key = "orders:order:" + orderId; |
| 106 | Object cached = redisTemplate.opsForValue().get(key); |
| 107 | if (cached == null) return Optional.empty(); |
| 108 | return Optional.of(objectMapper.convertValue(cached, OrderResponse.class)); |
| 109 | } |
| 110 | |
| 111 | public void put(OrderResponse order) { |
| 112 | String key = "orders:order:" + order.id(); |
| 113 | redisTemplate.opsForValue().set(key, order, TTL); |
| 114 | } |
| 115 | |
| 116 | public void evict(UUID orderId) { |
| 117 | redisTemplate.delete("orders:order:" + orderId); |
| 118 | } |
| 119 | } |
| 120 | ``` |
| 121 | |
| 122 | ## Rate Limiting with Redis |
| 123 | |
| 124 | ```java |
| 125 | @Component |
| 126 | @RequiredArgsConstructor |
| 127 | public class RateLimiter { |
| 128 | |
| 129 | private final RedisTemplate<String, String> redisTemplate; |
| 130 | |
| 131 | public boolean isAllowed(String identifier, int maxRequests, Duration window) { |
| 132 | String key = "ratelimit:" + identifier; |
| 133 | Long count = redisTemplate.opsForValue().increment(key); |
| 134 | if (count == 1) { |
| 135 | redisTemplate.expire(key, window); |
| 136 | } |
| 137 | return count <= maxRequests; |
| 138 | } |
| 139 | } |
| 140 | ``` |
| 141 | |
| 142 | ## application.yml |
| 143 | |
| 144 | ```yaml |
| 145 | spring: |
| 146 | data: |
| 147 | redis: |
| 148 | host: ${REDIS_HOST:localhost} |
| 149 | port: ${REDIS_PORT:6379} |
| 150 | password: ${REDIS_PASSWORD:} |
| 151 | timeout: 2000ms |
| 152 | lettuce: |
| 153 | pool: |
| 154 | max-active: 10 |
| 155 | max-idle: 5 |
| 156 | min-idle: 2 |
| 157 | cache: |
| 158 | type: redis |
| 159 | ``` |
| 160 | |
| 161 | ## Cache Stampede |
| 162 | |
| 163 | When a hot key expires, e |