0Pricing
Spring Boot 4 Complete Guide · บทเรียน

การแคชแบบกระจายด้วย Redis และ TTL

แชร์สถานะแคชระหว่างอินสแตนซ์โดยใช้ Redis เป็นแบ็กเอนด์แคชส่วนกลาง พร้อมควบคุมการทำซีเรียลไลซ์

การแคชแบบกระจายด้วย Redis และ TTL เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Distributed Caching?

Caffeine is a brilliant in-process cache: ultra-fast, but each application instance keeps its own private copy. The moment you scale horizontally to several pods, those copies drift apart.

  • Instance A evicts a user; instance B still serves the stale entry.
  • A cache warm-up on one node helps nobody else.
  • Total memory cost grows linearly with replica count.

A distributed cache solves this by putting cache state in a shared backend that every instance reads and writes. In Spring Boot, Redis is the most common choice for this role.

Adding the Redis Cache Starter

Spring Boot's caching abstraction is backend-agnostic. To swap Caffeine for Redis you mostly change dependencies and a property — your @Cacheable annotations stay the same.

Pull in the Redis starter and the cache abstraction:

  • spring-boot-starter-data-redis provides the connection and RedisCacheManager.
  • spring-boot-starter-cache enables the @Cacheable/@CacheEvict annotations.

Then declare Redis as the cache type so Boot auto-configures a RedisCacheManager instead of a simple map.

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

Configuring the Connection and Cache Type

Point Boot at your Redis server and tell the cache abstraction to use Redis. With spring.cache.type=redis, Boot wires a RedisCacheManager automatically.

  • spring.data.redis.host / port configure the Lettuce client (the default driver).
  • spring.cache.redis.time-to-live sets a default TTL for every entry.
  • spring.cache.cache-names can pre-declare caches at startup.
# application.yml
spring:
  data:
    redis:
      host: localhost
      port: 6379
  cache:
    type: redis
    cache-names: products, users
    redis:
      time-to-live: 10m
      cache-null-values: false
      use-key-prefix: true

The Same @Cacheable, a Shared Backend

This is the payoff of Spring's abstraction: the service code is identical to the Caffeine version. Only the CacheManager behind it changed.

Now when instance A populates products::42, instance B reads the very same key from Redis on its next call — no duplicate computation, no drift.

@Service
public class ProductService {

    private final ProductRepository repository;

    public ProductService(ProductRepository repository) {
        this.repository = repository;
    }

    @Cacheable(cacheNames = "products", key = "#id")
    public Product findById(Long id) {
        // Runs only on a cache miss across the whole cluster
        return repository.findById(id)
                .orElseThrow(() -> new ProductNotFoundException(id));
    }

    @CacheEvict(cacheNames = "products", key = "#product.id")
    public Product update(Product product) {
        return repository.save(product);
    }
}

TTLs: Bounding Staleness

A TTL (time-to-live) is the maximum age of a cache entry before Redis evicts it automatically. TTLs are the primary defense against serving stale data in a distributed cache.

  • Short TTL (seconds) → fresher data, more backend load.
  • Long TTL (hours) → cheaper, but staleness risk grows.
  • TTL is enforced server-side by Redis, so it applies uniformly to every instance.

Unlike Caffeine's expireAfterWrite, Redis TTLs survive a single instance restart because the data lives outside the JVM.

Per-Cache TTLs with a Custom RedisCacheManager

A single global TTL rarely fits every cache. Override the auto-configuration to give each cache its own expiry by supplying a RedisCacheManagerBuilderCustomizer (or a full RedisCacheManager bean).

Here products tolerates 30 minutes of staleness while volatile prices expires after 1 minute.

@Configuration
public class CacheConfig {

    @Bean
    public RedisCacheManagerBuilderCustomizer cacheCustomizer() {
        return builder -> builder
            .withCacheConfiguration("products",
                RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofMinutes(30)))
            .withCacheConfiguration("prices",
                RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofMinutes(1)));
    }
}

Serialization: How Values Reach Redis

Redis stores bytes, not Java objects. Every cached value must be serialized on write and deserialized on read. The default RedisCacheManager uses Java's native serialization (JdkSerializationRedisSerializer), which has real drawbacks:

  • Values are opaque binary blobs — unreadable with redis-cli.
  • The cached class must implement Serializable.
  • Tight coupling to class internals breaks across versions.

For interoperable, human-readable entries, switch the value serializer to JSON.

Controlling Serialization with JSON

Use GenericJackson2JsonRedisSerializer for values and a plain StringRedisSerializer for keys. JSON keeps entries inspectable and decouples them from Java class internals.

The serializer embeds type metadata (@class) so polymorphic values deserialize back to the correct concrete type.

@Bean
public RedisCacheConfiguration cacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(10))
        .disableCachingNullValues()
        .serializeKeysWith(
            RedisSerializationContext.SerializationPair.fromSerializer(
                new StringRedisSerializer()))
        .serializeValuesWith(
            RedisSerializationContext.SerializationPair.fromSerializer(
                new GenericJackson2JsonRedisSerializer()));
}

Key Prefixes Prevent Collisions

When several caches share one Redis database, their keys must not collide. By default Spring prefixes every entry with the cache name, so products::42 and users::42 stay separate.

  • use-key-prefix: true (default) keeps caches isolated.
  • You can supply a custom prefix, e.g. an app or tenant name, to share a Redis instance safely across services.

This matters most in multi-tenant or shared-infrastructure setups where one Redis serves many apps.

@Bean
public RedisCacheConfiguration cacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(10))
        .computePrefixWith(cacheName -> "shop:" + cacheName + "::");
    // key becomes shop:products::42
}

Avoiding the Thundering Herd

A distributed cache concentrates risk: when a hot key's TTL expires, every instance misses at once and stampedes the database — the thundering herd problem.

Mitigations:

  • Stagger TTLs by adding a small random jitter so keys don't expire together.
  • Refresh entries proactively before expiry rather than lazily on miss.
  • Use a short-lived lock so only one instance recomputes a missed key while others wait.

This pure-Java helper shows how to compute a jittered TTL you would feed into entryTtl(...).

import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

public class TtlJitter {

    static Duration withJitter(Duration base, double jitterFraction) {
        long baseMs = base.toMillis();
        long spread = (long) (baseMs * jitterFraction);
        long offset = ThreadLocalRandom.current().nextLong(-spread, spread + 1);
        return Duration.ofMillis(baseMs + offset);
    }

    public static void main(String[] args) {
        Duration base = Duration.ofMinutes(10);
        for (int i = 0; i < 3; i++) {
            Duration ttl = withJitter(base, 0.1); // +/- 10%
            System.out.println("TTL seconds: " + ttl.getSeconds());
        }
    }
}

Two-Tier Caching: Caffeine + Redis

You don't have to choose. A common production pattern is a two-tier (near) cache:

  • L1 — Caffeine in each instance, very short TTL, absorbs hot reads at nanosecond speed.
  • L2 — Redis, shared across the cluster, the source of truth for cached state.

A request checks Caffeine first; on a miss it falls back to Redis; on a Redis miss it hits the database. This cuts network round-trips while keeping the cluster consistent. Spring can compose this with a CompositeCacheManager or a dedicated near-cache library.

Quick Check: Choosing a TTL Strategy

Test your understanding of distributed cache trade-offs.

Recap: Distributed Caching with Redis

You moved from a private in-process cache to a shared, distributed one:

  • Why Redis: one cache state across all instances eliminates drift and duplicated work.
  • Drop-in swap: set spring.cache.type=redis and your @Cacheable code is unchanged.
  • TTLs: Redis enforces expiry server-side, uniformly across the cluster, surviving instance restarts; tune per cache with a RedisCacheManagerBuilderCustomizer.
  • Serialization: prefer GenericJackson2JsonRedisSerializer for readable, version-tolerant values over default JDK serialization.
  • Key prefixes isolate caches sharing one Redis; TTL jitter and two-tier Caffeine+Redis caches tame the thundering herd.

คำถามที่พบบ่อย

บทเรียน “การแคชแบบกระจายด้วย Redis และ TTL” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การแคชแบบกระจายด้วย Redis และ TTL” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การแคชแบบกระจายด้วย Redis และ TTL”

แชร์สถานะแคชระหว่างอินสแตนซ์โดยใช้ Redis เป็นแบ็กเอนด์แคชส่วนกลาง พร้อมควบคุมการทำซีเรียลไลซ์ คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การแคชแบบกระจายด้วย Redis และ TTL” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พื้นฐานนามธรรมแคชของ Spring
  2. การแคชในหน่วยความจำด้วยการปรับ Caffeine
  3. การแคชแบบกระจายด้วย Redis และ TTL
  4. แคชถล่ม การทำให้ใช้ไม่ได้ และความสอดคล้อง
← กลับไปที่ Spring Boot 4 Complete Guide