0Pricing
Spring Boot 4 Microservices & REST APIs · Lezione

Redis come provider della cache

Configuri una cache basata su Redis.

Redis come provider della cache è una lezione Spring Boot 4 Microservices & REST APIs gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Microservices & REST APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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=redis

Auto-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

Domande Frequenti

La lezione «Redis come provider della cache» è gratuita?

Sì — il testo completo di «Redis come provider della cache» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Microservices & REST APIs, passa a CoddyKit PRO. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Cosa imparerò in «Redis come provider della cache»?

Configuri una cache basata su Redis. Eserciti Spring Boot 4 Microservices & REST APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Boot 4 Microservices & REST APIs?

Non è richiesta alcuna esperienza precedente. Spring Boot 4 Microservices & REST APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Redis come provider della cache»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Microservices & REST APIs?

Sì. Ogni lezione Spring Boot 4 Microservices & REST APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. L'astrazione della cache di Spring
  2. @Cacheable, @CachePut, @CacheEvict
  3. Redis come provider della cache
  4. TTL e invalidazione della cache
← Torna a Spring Boot 4 Microservices & REST APIs