PHpullh
학습 라이브러리/Java/캐싱 (Caffeine)

JAVA · 성능/JVM

캐싱 (Caffeine)

Caffeine 라이브러리로 고성능 로컬 캐시를 구현합니다.

성능/JVM중급Caffeine캐시TTL성능

핵심 설명

Caffeine 라이브러리로 고성능 로컬 캐시를 구현합니다.

Java code

// Caffeine 의존성: com.github.ben-manes.caffeine:caffeine:3.1+

// import com.github.ben-manes.caffeine.cache.*;

// Caffeine 캐시 설정 (의사코드)
// Cache<String, User> cache = Caffeine.newBuilder()
//     .maximumSize(10_000)              // 최대 항목 수
//     .expireAfterWrite(Duration.ofMinutes(5))  // 쓰기 후 만료
//     .expireAfterAccess(Duration.ofMinutes(1)) // 접근 후 만료
//     .recordStats()                    // 통계 기록
//     .build();

// 동기 로딩 캐시
// LoadingCache<String, User> loadingCache = Caffeine.newBuilder()
//     .maximumSize(10_000)
//     .expireAfterWrite(Duration.ofMinutes(5))
//     .build(key -> userRepository.findById(key)); // 캐시 미스 시 로딩

// 비동기 로딩 캐시
// AsyncLoadingCache<String, User> asyncCache = Caffeine.newBuilder()
//     .maximumSize(10_000)
//     .buildAsync(key -> userRepository.findByIdAsync(key));

// 간단한 캐시 구현
import java.util.*;
import java.util.concurrent.*;

class SimpleCache<K, V> {
    private final Map<K, V> store = new ConcurrentHashMap<>();
    private final Map<K, Long> expiry = new ConcurrentHashMap<>();
    private final long ttlMs;

    SimpleCache(long ttlMs) { this.ttlMs = ttlMs; }

    void put(K key, V value) {
        store.put(key, value);
        expiry.put(key, System.currentTimeMillis() + ttlMs);
    }

    Optional<V> get(K key) {
        Long exp = expiry.get(key);
        if (exp == null || System.currentTimeMillis() > exp) {
            store.remove(key);
            expiry.remove(key);
            return Optional.empty();
        }
        return Optional.ofNullable(store.get(key));
    }
}

class Main {
    public static void main(String[] args) {
        SimpleCache<String, String> cache = new SimpleCache<>(5000);
        cache.put("key", "value");
        System.out.println(cache.get("key")); // Optional[value]
    }
}

학습 팁

Caffeine은 W-TinyLFU 알고리즘으로 높은 적중률을 제공합니다. 로컬 캐시로는 Caffeine이 최고 성능입니다.

주의할 점

캐시 크기를 너무 크게 설정하면 GC 부담이 늘어납니다. 힙의 10-20% 이내로 유지하고 모니터링하세요.

자주 묻는 질문

캐싱 (Caffeine)란 무엇인가요?

Caffeine 라이브러리로 고성능 로컬 캐시를 구현합니다.

캐싱 (Caffeine) 학습 시 주의할 점은 무엇인가요?

캐시 크기를 너무 크게 설정하면 GC 부담이 늘어납니다. 힙의 10-20% 이내로 유지하고 모니터링하세요.