Redis como proveedor de caché
Configure el almacenamiento en caché respaldado por Redis
Redis como proveedor de caché es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Redis for Caching
Redis is an in-memory data store that works as a distributed cache shared across many app instances.
- Survives app restarts
- Shared by all nodes
- Supports TTL and eviction
Adding the Dependency
Add Spring Data Redis to switch the cache backend to Redis.
// build.gradle
implementation "org.springframework.boot:spring-boot-starter-data-redis"Connection Settings
Point Spring at your Redis server in properties.
# application.properties
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.cache.type=redisAuto-Configured RedisCacheManager
With Redis on the classpath and spring.cache.type=redis, Spring Boot auto-configures a RedisCacheManager. Your existing @Cacheable methods now use Redis with no code change.
Customizing the CacheManager
Define a RedisCacheManager bean for fine control over defaults.
@Bean
public RedisCacheManager cacheManager(
RedisConnectionFactory factory) {
RedisCacheConfiguration config =
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}Serialization
Cached values are serialized before storage. JDK serialization is the default; JSON is more portable and readable.
RedisCacheConfiguration config =
RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(
SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()));Serializable Entities
For JDK serialization, cached objects must implement Serializable. JSON serialization avoids this requirement.
public class Product implements Serializable {
private Long id;
private String name;
}Key Prefixes
Redis cache keys are prefixed with the cache name by default (e.g. products::1), keeping caches namespaced in the shared store.
Per-Cache Configuration
Give individual caches their own TTL via a map of configurations.
Map<String, RedisCacheConfiguration> configs =
Map.of("products",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)));
return RedisCacheManager.builder(factory)
.withInitialCacheConfigurations(configs)
.build();RedisTemplate for Direct Access
Beyond the cache abstraction, RedisTemplate lets you read and write Redis directly.
@Autowired
RedisTemplate<String, String> redisTemplate;
redisTemplate.opsForValue()
.set("greeting", "hello",
Duration.ofSeconds(30));Resilience to Redis Outages
If Redis is unreachable, cache operations fail. Consider a fallback strategy or error handler so a cache outage does not take down the app.
Quick Check
Test your understanding of Redis caching.
Recap
You learned to use Redis as a cache:
- Add the data-redis starter, set
spring.cache.type=redis - Auto-configured
RedisCacheManager - Customize TTL and JSON serialization via a bean
- Keys are namespaced by cache name
Preguntas frecuentes
¿La lección «Redis como proveedor de caché» es gratis?
Sí — el texto completo de «Redis como proveedor de caché» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
¿Qué aprenderé en «Redis como proveedor de caché»?
Configure el almacenamiento en caché respaldado por Redis Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?
No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Redis como proveedor de caché»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?
Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- La abstracción de caché de Spring
- @Cacheable, @CachePut, @CacheEvict
- Redis como proveedor de caché
- TTL e invalidación de la caché