콘텐츠 대표 이미지 - 자바 캐싱과 Redis·Hazelcast를 활용한 성능 최적화
☕ Java × Cache × Redis × Hazelcast

자바 캐싱과 Redis·Hazelcast를 활용한 성능 최적화

느린 서버는 이제 그만 🚀 캐시 마스터가 되는 완전 가이드
⚡🗄️🔥💾🛠️
클라이언트 요청 발생 👤 요청 캐시 레이어 Redis / Hazelcast 로컬 캐시 ⚡ 캐시 미스 데이터베이스 원본 데이터 🗄️ 캐시 저장 후 응답 성능 비교 DB 직접 100ms 캐시 사용 1ms 이하 ⚡ 100배 빠름!
🤔 캐싱이 뭔데? 왜 이렇게 난리야?

솔직히 말하면, 캐싱은 개발자들 사이에서 "성능 문제의 80%를 해결하는 마법"이라고 불릴 정도야. 근데 막상 제대로 이해하고 쓰는 사람은 생각보다 많지 않음 ㅋㅋ

캐싱(Caching)이란 자주 사용되는 데이터를 빠른 저장소에 미리 저장해두고, 같은 요청이 오면 원본 소스(DB, API 등)에 다시 접근하지 않고 저장된 데이터를 바로 돌려주는 기법이야.

예를 들어볼게. 네가 매일 아침 편의점에서 같은 삼각김밥을 사는데, 편의점 직원이 매번 창고에서 꺼내온다면? 시간 낭비잖아. 근데 카운터 앞에 미리 꺼내놓으면? 바로 집어갈 수 있지. 이게 바로 캐싱의 개념이야 😄

💡 캐싱의 핵심: 느린 저장소(DB, 파일, 외부 API)에 대한 접근 횟수를 줄여서 응답 속도를 극적으로 향상시키는 것!
📊 캐싱이 필요한 상황들

아래 상황 중 하나라도 해당되면 캐싱을 진지하게 고려해야 해:

1
동일한 DB 쿼리가 반복적으로 실행될 때
예: 메인 페이지 배너 데이터, 카테고리 목록, 공지사항 등 자주 바뀌지 않는 데이터
2
외부 API 호출이 느리거나 비용이 발생할 때
예: 날씨 API, 환율 API, 지도 API 등 실시간성이 크게 중요하지 않은 경우
3
복잡한 연산 결과를 재사용할 때
예: 통계 집계, 추천 알고리즘 결과, 복잡한 비즈니스 로직 계산값
4
트래픽이 급증하는 상황
예: 이벤트, 세일, 뉴스 기사 바이럴 등 특정 시점에 동일 데이터 요청이 폭발적으로 증가

☕ Java에서 캐싱 구현하기 - 기초부터 고급까지
🔰 Level 1: 가장 단순한 로컬 캐시 - HashMap

처음엔 다들 이렇게 시작해. HashMap으로 직접 캐시 구현하는 거 ㅋㅋ 단순하지만 개념 이해에는 최고야:


// 가장 기본적인 캐시 구현
public class SimpleCache {
    private Map<String, Object> cache = new HashMap<>();
    
    public Object get(String key) {
        return cache.get(key);
    }
    
    public void put(String key, Object value) {
        cache.put(key, value);
    }
    
    public boolean containsKey(String key) {
        return cache.containsKey(key);
    }
}

// 사용 예시
public class UserService {
    private SimpleCache cache = new SimpleCache();
    
    public User getUserById(Long id) {
        String key = "user:" + id;
        
        // 캐시에서 먼저 확인
        if (cache.containsKey(key)) {
            return (User) cache.get(key);  // 캐시 히트!
        }
        
        // 캐시 미스 - DB에서 조회
        User user = userRepository.findById(id);
        cache.put(key, user);  // 캐시에 저장
        return user;
    }
}
    
⚠️ 이 방식의 문제점: 만료 시간(TTL) 없음, 메모리 무한 증가, 멀티스레드 안전하지 않음, 서버 재시작 시 데이터 소실. 실제 프로덕션에서는 절대 이렇게 쓰면 안 됨!
🔰 Level 2: ConcurrentHashMap + 만료 시간 구현

멀티스레드 환경을 고려하고 TTL(Time To Live)을 추가해보자:


import java.util.concurrent.ConcurrentHashMap;
import java.time.Instant;

public class TTLCache<K, V> {
    
    private static class CacheEntry<V> {
        final V value;
        final Instant expiresAt;
        
        CacheEntry(V value, long ttlSeconds) {
            this.value = value;
            this.expiresAt = Instant.now().plusSeconds(ttlSeconds);
        }
        
        boolean isExpired() {
            return Instant.now().isAfter(expiresAt);
        }
    }
    
    private final ConcurrentHashMap<K, CacheEntry<V>> store = 
        new ConcurrentHashMap<>();
    private final long defaultTtlSeconds;
    
    public TTLCache(long defaultTtlSeconds) {
        this.defaultTtlSeconds = defaultTtlSeconds;
    }
    
    public void put(K key, V value) {
        store.put(key, new CacheEntry<>(value, defaultTtlSeconds));
    }
    
    public Optional<V> get(K key) {
        CacheEntry<V> entry = store.get(key);
        if (entry == null || entry.isExpired()) {
            store.remove(key);  // 만료된 항목 제거
            return Optional.empty();
        }
        return Optional.of(entry.value);
    }
}
    
✅ ConcurrentHashMap을 사용하면 멀티스레드 환경에서 안전하게 캐시를 운영할 수 있어. 하지만 여전히 분산 환경에서는 한계가 있음.
🚀 Level 3: Caffeine - 자바 최강 로컬 캐시 라이브러리

Caffeine은 현재 Java 생태계에서 가장 성능이 뛰어난 로컬 캐시 라이브러리야. Google Guava Cache의 후계자격이고, Spring Boot 2.x 이후로 기본 캐시 구현체로 채택됐어. 진짜 미쳤음 ㅋㅋ


// build.gradle 의존성 추가
// implementation 'com.github.ben-manes.caffeine:caffeine:3.1.8'

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;

public class CaffeineExample {
    
    // 기본 캐시 생성
    Cache<String, User> userCache = Caffeine.newBuilder()
        .maximumSize(10_000)           // 최대 10,000개 항목
        .expireAfterWrite(10, TimeUnit.MINUTES)  // 쓰기 후 10분 만료
        .expireAfterAccess(5, TimeUnit.MINUTES)  // 접근 후 5분 만료
        .recordStats()                 // 통계 수집
        .build();
    
    // LoadingCache - 자동 로딩 기능
    LoadingCache<String, User> loadingCache = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build(key -> userRepository.findByUsername(key));  // 캐시 미스 시 자동 로드
    
    public User getUser(String username) {
        // get()은 캐시 미스 시 null 반환
        return userCache.get(username, k -> userRepository.findByUsername(k));
    }
    
    // 캐시 통계 확인
    public void printStats() {
        CacheStats stats = userCache.stats();
        System.out.println("히트율: " + stats.hitRate());
        System.out.println("히트 횟수: " + stats.hitCount());
        System.out.println("미스 횟수: " + stats.missCount());
        System.out.println("평균 로드 시간: " + stats.averageLoadPenalty());
    }
}
    
🏆 Caffeine의 핵심 알고리즘: W-TinyLFU(Window TinyLFU) - LRU와 LFU의 장점을 결합한 알고리즘으로, 실제 벤치마크에서 Guava Cache 대비 최대 10배 이상 처리량이 높아!
🌿 Spring Cache Abstraction - 어노테이션으로 캐시 뚝딱!

Spring에서는 캐시 추상화 레이어를 제공해서, 어노테이션 몇 개만으로 캐싱을 구현할 수 있어. 코드 변경 최소화! 이게 진짜 개꿀임 ㅋㅋ


// application.yml 설정
spring:
  cache:
    type: caffeine
    caffeine:
      spec: maximumSize=10000,expireAfterWrite=600s

// @EnableCaching 활성화
@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// 서비스 레이어에서 캐시 어노테이션 사용
@Service
public class ProductService {
    
    // 캐시에서 조회, 없으면 메서드 실행 후 캐시 저장
    @Cacheable(value = "products", key = "#id")
    public Product getProduct(Long id) {
        System.out.println("DB 조회 중..."); // 캐시 히트 시 이 줄은 실행 안 됨!
        return productRepository.findById(id).orElseThrow();
    }
    
    // 캐시 업데이트 (메서드 실행 후 캐시 갱신)
    @CachePut(value = "products", key = "#product.id")
    public Product updateProduct(Product product) {
        return productRepository.save(product);
    }
    
    // 캐시 삭제
    @CacheEvict(value = "products", key = "#id")
    public void deleteProduct(Long id) {
        productRepository.deleteById(id);
    }
    
    // 여러 캐시 동시에 삭제
    @Caching(evict = {
        @CacheEvict(value = "products", key = "#id"),
        @CacheEvict(value = "productList", allEntries = true)
    })
    public void deleteProductAndClearList(Long id) {
        productRepository.deleteById(id);
    }
    
    // 조건부 캐싱
    @Cacheable(value = "products", key = "#id", 
               condition = "#id > 0",
               unless = "#result == null")
    public Product getProductConditional(Long id) {
        return productRepository.findById(id).orElse(null);
    }
}
    
✅ Spring Cache Abstraction의 장점: 캐시 구현체를 나중에 바꿔도 비즈니스 코드 수정 없음! Caffeine → Redis → Hazelcast 전환이 설정 파일 변경만으로 가능해.

Redis 아키텍처 구조 Redis 서버 인메모리 데이터 스토어 String / Hash / List / Set / ZSet 🔴 앱 서버 1 Java Spring ☕ 앱 서버 2 Java Spring ☕ 앱 서버 3 Java Spring ☕ 앱 서버 4 Java Spring ☕ String 키-값 저장 Hash 객체 저장 List 순서 있는 목록 Set 중복 없는 집합 Sorted Set 점수 기반 정렬 Pub/Sub 메시지 브로커 모든 앱 서버가 하나의 Redis를 공유 → 분산 캐시 실현!
🔴 Redis - 분산 캐시의 왕

Redis(Remote Dictionary Server)는 인메모리 데이터 구조 저장소야. 2009년 Salvatore Sanfilippo가 만들었고, 현재 전 세계에서 가장 많이 사용되는 캐시 솔루션이야. 왜 이렇게 인기 있냐고? 이유가 있지 ㅋㅋ

🏆 Redis의 핵심 특징: 초당 100만 건 이상의 읽기/쓰기 처리, 단일 스레드 이벤트 루프로 원자적 연산 보장, 다양한 데이터 구조 지원, 영속성(Persistence) 옵션 제공
⚙️ Spring Boot + Redis 설정하기

// build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-cache'
}

// application.yml
spring:
  redis:
    host: localhost
    port: 6379
    password: your-password  # 운영환경에서는 반드시 설정!
    timeout: 2000ms
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

// Redis 설정 클래스
@Configuration
@EnableCaching
public class RedisConfig {
    
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName("localhost");
        config.setPort(6379);
        
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config);
        return factory;
    }
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        // 직렬화 설정 (JSON 방식 권장)
        Jackson2JsonRedisSerializer<Object> serializer = 
            new Jackson2JsonRedisSerializer<>(Object.class);
        
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        
        return template;
    }
    
    // Spring Cache와 연동
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(10))  // 기본 TTL 10분
            .serializeKeysWith(
                RedisSerializationContext.SerializationPair
                    .fromSerializer(new StringRedisSerializer()))
            .serializeValuesWith(
                RedisSerializationContext.SerializationPair
                    .fromSerializer(new GenericJackson2JsonRedisSerializer()))
            .disableCachingNullValues();  // null 값 캐싱 방지
        
        // 캐시별 개별 TTL 설정
        Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
        cacheConfigs.put("users", config.entryTtl(Duration.ofHours(1)));
        cacheConfigs.put("products", config.entryTtl(Duration.ofMinutes(30)));
        cacheConfigs.put("sessions", config.entryTtl(Duration.ofDays(1)));
        
        return RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(config)
            .withInitialCacheConfigurations(cacheConfigs)
            .build();
    }
}
    
🛠️ RedisTemplate 직접 활용하기

어노테이션 방식 외에도 RedisTemplate을 직접 사용하면 더 세밀한 제어가 가능해:


@Service
@RequiredArgsConstructor
public class RedisService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    private final StringRedisTemplate stringRedisTemplate;
    
    // === String 타입 조작 ===
    public void setString(String key, String value, long ttlSeconds) {
        stringRedisTemplate.opsForValue()
            .set(key, value, Duration.ofSeconds(ttlSeconds));
    }
    
    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
    
    // === Hash 타입 - 객체 저장에 유용 ===
    public void setHash(String key, String field, Object value) {
        redisTemplate.opsForHash().put(key, field, value);
    }
    
    public Object getHash(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }
    
    public Map<Object, Object> getAllHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
    
    // === List 타입 - 큐/스택 구현 ===
    public void pushToList(String key, Object value) {
        redisTemplate.opsForList().rightPush(key, value);
    }
    
    public Object popFromList(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }
    
    // === Sorted Set - 랭킹 시스템 ===
    public void addToRanking(String key, String member, double score) {
        redisTemplate.opsForZSet().add(key, member, score);
    }
    
    public Set<Object> getTopRanking(String key, int count) {
        return redisTemplate.opsForZSet()
            .reverseRange(key, 0, count - 1);
    }
    
    // === 분산 락 구현 ===
    public boolean tryLock(String lockKey, String lockValue, long ttlSeconds) {
        Boolean result = stringRedisTemplate.opsForValue()
            .setIfAbsent(lockKey, lockValue, Duration.ofSeconds(ttlSeconds));
        return Boolean.TRUE.equals(result);
    }
    
    public void releaseLock(String lockKey, String lockValue) {
        String currentValue = stringRedisTemplate.opsForValue().get(lockKey);
        if (lockValue.equals(currentValue)) {
            stringRedisTemplate.delete(lockKey);
        }
    }
    
    // === TTL 관리 ===
    public Long getTTL(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
    
    public void extendTTL(String key, long additionalSeconds) {
        Long currentTTL = getTTL(key);
        if (currentTTL != null && currentTTL > 0) {
            redisTemplate.expire(key, 
                currentTTL + additionalSeconds, TimeUnit.SECONDS);
        }
    }
}
    
✅ Redis의 Sorted Set(ZSet)은 실시간 랭킹 시스템 구현에 최적화되어 있어. 게임 리더보드, 인기 상품 순위 등에 딱이야!
⚡ Redis 고급 패턴들

1. Cache-Aside 패턴 (가장 일반적)


@Service
public class ProductCacheService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    private final ProductRepository productRepository;
    
    public Product getProduct(Long id) {
        String cacheKey = "product:" + id;
        
        // 1. 캐시 조회
        Product cached = (Product) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;  // 캐시 히트
        }
        
        // 2. DB 조회 (캐시 미스)
        Product product = productRepository.findById(id)
            .orElseThrow(() -> new ProductNotFoundException(id));
        
        // 3. 캐시 저장 (TTL 30분)
        redisTemplate.opsForValue().set(cacheKey, product, Duration.ofMinutes(30));
        
        return product;
    }
}
    

2. Write-Through 패턴


// 데이터 변경 시 DB와 캐시를 동시에 업데이트
public Product updateProduct(Long id, ProductUpdateRequest request) {
    // DB 업데이트
    Product product = productRepository.findById(id).orElseThrow();
    product.update(request);
    productRepository.save(product);
    
    // 캐시도 즉시 업데이트
    String cacheKey = "product:" + id;
    redisTemplate.opsForValue().set(cacheKey, product, Duration.ofMinutes(30));
    
    return product;
}
    

3. Cache Stampede 방지 (Probabilistic Early Expiration)


// 캐시 만료 직전에 확률적으로 미리 갱신하여 동시 DB 접근 방지
public Product getProductWithStampedeProtection(Long id) {
    String cacheKey = "product:" + id;
    Long ttl = redisTemplate.getExpire(cacheKey, TimeUnit.SECONDS);
    
    // TTL이 30초 미만이면 20% 확률로 미리 갱신
    if (ttl != null && ttl < 30 && Math.random() < 0.2) {
        Product freshProduct = productRepository.findById(id).orElseThrow();
        redisTemplate.opsForValue().set(cacheKey, freshProduct, Duration.ofMinutes(30));
        return freshProduct;
    }
    
    Product cached = (Product) redisTemplate.opsForValue().get(cacheKey);
    if (cached != null) return cached;
    
    Product product = productRepository.findById(id).orElseThrow();
    redisTemplate.opsForValue().set(cacheKey, product, Duration.ofMinutes(30));
    return product;
}
    

Hazelcast 분산 클러스터 구조 Hazelcast 클러스터 노드 1 (마스터) 데이터 파티션 1,2,3 🔵 노드 2 데이터 파티션 4,5,6 🔵 노드 3 데이터 파티션 7,8,9 🔵 ⚡ 자동 파티셔닝 데이터 자동 분산 저장 🔄 자동 복제 노드 장애 시 자동 복구 📈 수평 확장 노드 추가로 용량 증가 🔒 분산 락 클러스터 전체 동기화
🔵 Hazelcast - 분산 컴퓨팅의 강자

Hazelcast는 Java 기반의 오픈소스 인메모리 데이터 그리드(IMDG)야. Redis와 달리 JVM 프로세스 내부에 임베디드로 실행할 수 있어서 네트워크 오버헤드가 없다는 게 큰 장점이야. 물론 클라이언트-서버 모드도 지원해.

Hazelcast의 가장 큰 특징은 자동 데이터 파티셔닝이야. 클러스터에 노드를 추가하면 데이터가 자동으로 재분배되고, 노드가 죽으면 다른 노드에 복제된 데이터로 자동 복구돼. 진짜 신기하지 않음? ㅋㅋ

🎯 Hazelcast vs Redis 핵심 차이: Hazelcast는 JVM 내장 가능(임베디드 모드), 자동 클러스터링, Java 객체 직렬화 없이 사용 가능. Redis는 별도 서버 필요하지만 더 다양한 데이터 구조와 성숙한 생태계 보유.
⚙️ Hazelcast 설정 및 기본 사용법

// build.gradle
dependencies {
    implementation 'com.hazelcast:hazelcast:5.3.6'
    implementation 'com.hazelcast:hazelcast-spring:5.3.6'
}

// Hazelcast 설정 클래스
@Configuration
@EnableCaching
public class HazelcastConfig {
    
    @Bean
    public HazelcastInstance hazelcastInstance() {
        Config config = new Config();
        config.setInstanceName("my-hazelcast-instance");
        
        // 네트워크 설정
        NetworkConfig networkConfig = config.getNetworkConfig();
        networkConfig.setPort(5701);
        networkConfig.setPortAutoIncrement(true);
        
        // 클러스터 멤버 자동 발견 (멀티캐스트)
        JoinConfig joinConfig = networkConfig.getJoin();
        joinConfig.getMulticastConfig().setEnabled(true);
        
        // 또는 TCP/IP 방식으로 멤버 지정
        // joinConfig.getMulticastConfig().setEnabled(false);
        // joinConfig.getTcpIpConfig()
        //     .setEnabled(true)
        //     .addMember("192.168.1.1")
        //     .addMember("192.168.1.2");
        
        // Map 캐시 설정
        MapConfig mapConfig = new MapConfig("products");
        mapConfig.setTimeToLiveSeconds(1800);  // 30분 TTL
        mapConfig.setMaxIdleSeconds(600);       // 10분 미접근 시 만료
        mapConfig.setEvictionConfig(
            new EvictionConfig()
                .setEvictionPolicy(EvictionPolicy.LRU)
                .setMaxSizePolicy(MaxSizePolicy.PER_NODE)
                .setSize(10000)
        );
        
        // 백업 설정 (다른 노드에 복제본 유지)
        mapConfig.setBackupCount(1);  // 1개 동기 백업
        mapConfig.setAsyncBackupCount(0);
        
        config.addMapConfig(mapConfig);
        
        return Hazelcast.newHazelcastInstance(config);
    }
    
    // Spring Cache와 연동
    @Bean
    public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
        return new HazelcastCacheManager(hazelcastInstance);
    }
}
    
🛠️ Hazelcast 분산 자료구조 활용

@Service
@RequiredArgsConstructor
public class HazelcastService {
    
    private final HazelcastInstance hazelcastInstance;
    
    // === IMap - 분산 HashMap ===
    public void putToMap(String mapName, String key, Object value) {
        IMap<String, Object> map = hazelcastInstance.getMap(mapName);
        map.put(key, value, 30, TimeUnit.MINUTES);  // TTL 30분
    }
    
    public Object getFromMap(String mapName, String key) {
        IMap<String, Object> map = hazelcastInstance.getMap(mapName);
        return map.get(key);
    }
    
    // 조건부 업데이트 (원자적 연산)
    public boolean updateIfExists(String mapName, String key, Object newValue) {
        IMap<String, Object> map = hazelcastInstance.getMap(mapName);
        Object oldValue = map.get(key);
        if (oldValue != null) {
            return map.replace(key, oldValue, newValue);
        }
        return false;
    }
    
    // === IQueue - 분산 큐 ===
    public void enqueue(String queueName, Object item) {
        IQueue<Object> queue = hazelcastInstance.getQueue(queueName);
        queue.offer(item);
    }
    
    public Object dequeue(String queueName) {
        IQueue<Object> queue = hazelcastInstance.getQueue(queueName);
        return queue.poll();
    }
    
    // === IAtomicLong - 분산 카운터 ===
    public long incrementCounter(String counterName) {
        IAtomicLong counter = hazelcastInstance.getCPSubsystem()
            .getAtomicLong(counterName);
        return counter.incrementAndGet();
    }
    
    // === 분산 락 ===
    public void executeWithLock(String lockName, Runnable task) {
        FencedLock lock = hazelcastInstance.getCPSubsystem()
            .getLock(lockName);
        lock.lock();
        try {
            task.run();
        } finally {
            lock.unlock();
        }
    }
    
    // === 분산 실행 (Executor Service) ===
    public <T> Future<T> executeOnCluster(Callable<T> task) {
        IExecutorService executorService = 
            hazelcastInstance.getExecutorService("default");
        return executorService.submit(task);
    }
    
    // === 엔트리 리스너 - 캐시 변경 감지 ===
    public void addEntryListener(String mapName) {
        IMap<String, Object> map = hazelcastInstance.getMap(mapName);
        map.addEntryListener(new EntryAddedListener<String, Object>() {
            @Override
            public void entryAdded(EntryEvent<String, Object> event) {
                System.out.println("새 항목 추가: " + event.getKey());
            }
        }, true);
    }
}
    
✅ Hazelcast의 분산 락(FencedLock)은 네트워크 파티션 상황에서도 안전하게 동작해. CP Subsystem을 활성화하면 Raft 합의 알고리즘 기반으로 강력한 일관성을 보장해!

⚔️ Redis vs Hazelcast - 뭘 써야 해?

이게 진짜 많이 물어보는 질문이야. 정답은 없고 상황에 따라 다른데, 아래 비교표를 보면 선택이 쉬워질 거야 ㅋㅋ

비교 항목 🔴 Redis 🔵 Hazelcast
실행 방식 별도 서버 프로세스 필수 임베디드 또는 별도 서버
언어 C 언어 (고성능) Java (JVM 기반)
데이터 구조 String, Hash, List, Set, ZSet, Stream 등 Map, Queue, Set, List, MultiMap 등
클러스터링 Redis Cluster (수동 설정) 자동 클러스터 형성
영속성 RDB, AOF 지원 Hot Restart (엔터프라이즈)
분산 연산 Lua 스크립트 Java 코드 직접 실행
Spring 통합 Spring Data Redis (매우 성숙) Hazelcast Spring (잘 지원)
적합한 상황 다양한 언어 혼용, 성숙한 생태계 필요 순수 Java 환경, 임베디드 캐시 필요
라이선스 Redis Source Available License (7.x) Apache 2.0 (오픈소스)
⚠️ Redis 7.x부터 라이선스가 변경됐어! 상업적 사용 시 주의가 필요해. 이 때문에 Valkey(Redis 포크)나 Hazelcast로 전환을 고려하는 팀들이 늘고 있어.

🏗️ 멀티레이어 캐싱 전략 - 진짜 고수들의 방법

실제 대규모 서비스에서는 로컬 캐시 + 분산 캐시를 함께 사용하는 멀티레이어 캐싱을 써. 이걸 L1/L2 캐시라고도 부르는데, 각 레이어의 장점을 극대화하는 방식이야.

🎯 멀티레이어 캐싱 원리: L1(로컬 Caffeine) → L2(Redis/Hazelcast) → DB 순서로 조회. 히트율이 높을수록 빠른 레이어에서 응답!
멀티레이어 캐싱 흐름 클라이언트 👤 L1 캐시 로컬 Caffeine 응답: ~0.1ms ⚡ 미스 L2 캐시 Redis / Hazelcast 응답: ~1ms 🔴 미스 데이터베이스 원본 데이터 응답: ~100ms 🗄️ 히트율 ~80% 대부분 여기서 해결 히트율 ~15% L1 미스 처리 히트율 ~5% 실제 DB 접근 전체 효과 DB 부하 95% 감소!
💻 멀티레이어 캐시 구현 코드

@Service
@RequiredArgsConstructor
public class MultiLayerCacheService {
    
    // L1: 로컬 Caffeine 캐시
    private final Cache<String, Object> localCache = Caffeine.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(5, TimeUnit.MINUTES)  // L1은 짧은 TTL
        .build();
    
    // L2: Redis 분산 캐시
    private final RedisTemplate<String, Object> redisTemplate;
    private final ProductRepository productRepository;
    
    public Product getProduct(Long id) {
        String cacheKey = "product:" + id;
        
        // 1단계: L1 캐시 조회 (가장 빠름, ~0.1ms)
        Product l1Result = (Product) localCache.getIfPresent(cacheKey);
        if (l1Result != null) {
            return l1Result;  // L1 캐시 히트!
        }
        
        // 2단계: L2 캐시 조회 (Redis, ~1ms)
        Product l2Result = (Product) redisTemplate.opsForValue().get(cacheKey);
        if (l2Result != null) {
            // L2 히트 → L1에도 저장 (다음 요청은 L1에서 처리)
            localCache.put(cacheKey, l2Result);
            return l2Result;  // L2 캐시 히트!
        }
        
        // 3단계: DB 조회 (캐시 미스, ~100ms)
        Product product = productRepository.findById(id)
            .orElseThrow(() -> new ProductNotFoundException(id));
        
        // L2 저장 (30분 TTL)
        redisTemplate.opsForValue().set(cacheKey, product, Duration.ofMinutes(30));
        // L1 저장 (5분 TTL)
        localCache.put(cacheKey, product);
        
        return product;
    }
    
    // 캐시 무효화 (L1, L2 모두)
    public void invalidateCache(Long id) {
        String cacheKey = "product:" + id;
        localCache.invalidate(cacheKey);
        redisTemplate.delete(cacheKey);
    }
    
    // 패턴 기반 캐시 무효화
    public void invalidateCacheByPattern(String pattern) {
        // L1 전체 무효화 (패턴 지원 어려움)
        localCache.invalidateAll();
        
        // L2 패턴 기반 삭제
        Set<String> keys = redisTemplate.keys(pattern + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
    
⚠️ 주의: L1과 L2의 TTL을 다르게 설정해야 해! L1은 짧게(5분), L2는 길게(30분). 그래야 L1 만료 후 L2에서 다시 가져올 수 있어. L1 TTL이 L2보다 길면 의미가 없음!

🚨 캐시 관련 주요 문제들과 해결책
💥 1. Cache Stampede (캐시 스탬피드)

캐시가 만료되는 순간 수천 개의 요청이 동시에 DB로 몰리는 현상이야. 마치 콘서트 티켓 오픈 순간 서버가 터지는 것처럼 ㅋㅋ


// 해결책 1: 분산 락을 이용한 단일 DB 접근
@Service
public class StampedeProtectedService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    private final StringRedisTemplate stringRedisTemplate;
    
    public Product getProductSafe(Long id) {
        String cacheKey = "product:" + id;
        String lockKey = "lock:product:" + id;
        
        // 캐시 조회
        Product cached = (Product) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) return cached;
        
        // 락 획득 시도 (5초 TTL)
        Boolean lockAcquired = stringRedisTemplate.opsForValue()
            .setIfAbsent(lockKey, "locked", Duration.ofSeconds(5));
        
        if (Boolean.TRUE.equals(lockAcquired)) {
            try {
                // 락 획득 성공 → DB 조회 및 캐시 저장
                Product product = productRepository.findById(id).orElseThrow();
                redisTemplate.opsForValue()
                    .set(cacheKey, product, Duration.ofMinutes(30));
                return product;
            } finally {
                stringRedisTemplate.delete(lockKey);
            }
        } else {
            // 락 획득 실패 → 잠시 대기 후 캐시 재조회
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return getProductSafe(id);  // 재귀 호출
        }
    }
}
    
💥 2. Cache Penetration (캐시 관통)

존재하지 않는 키로 계속 요청이 들어와서 캐시를 우회하고 DB에 직접 부하를 주는 공격 패턴이야. 악의적인 사용자가 의도적으로 할 수도 있어.


// 해결책: Null 캐싱 + Bloom Filter
@Service
public class PenetrationProtectedService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    private static final String NULL_VALUE = "NULL_PLACEHOLDER";
    
    // 방법 1: Null 값도 캐싱 (짧은 TTL로)
    public Product getProductWithNullCache(Long id) {
        String cacheKey = "product:" + id;
        
        Object cached = redisTemplate.opsForValue().get(cacheKey);
        
        if (NULL_VALUE.equals(cached)) {
            return null;  // 존재하지 않는 데이터임을 캐시에서 확인
        }
        
        if (cached != null) {
            return (Product) cached;
        }
        
        Product product = productRepository.findById(id).orElse(null);
        
        if (product == null) {
            // null도 캐싱 (짧은 TTL: 1분)
            redisTemplate.opsForValue()
                .set(cacheKey, NULL_VALUE, Duration.ofMinutes(1));
        } else {
            redisTemplate.opsForValue()
                .set(cacheKey, product, Duration.ofMinutes(30));
        }
        
        return product;
    }
}

// 방법 2: Bloom Filter로 존재 여부 사전 확인
// Redisson 라이브러리 활용
@Service
public class BloomFilterService {
    
    private final RedissonClient redissonClient;
    
    @PostConstruct
    public void initBloomFilter() {
        RBloomFilter<Long> bloomFilter = 
            redissonClient.getBloomFilter("product-ids");
        // 예상 원소 수: 100만, 오탐률: 1%
        bloomFilter.tryInit(1_000_000L, 0.01);
        
        // 기존 상품 ID 모두 추가
        productRepository.findAllIds()
            .forEach(bloomFilter::add);
    }
    
    public Product getProductWithBloomFilter(Long id) {
        RBloomFilter<Long> bloomFilter = 
            redissonClient.getBloomFilter("product-ids");
        
        // Bloom Filter에 없으면 DB 조회 없이 바로 null 반환
        if (!bloomFilter.contains(id)) {
            return null;
        }
        
        // 존재 가능성 있음 → 캐시/DB 조회
        return getProductFromCacheOrDB(id);
    }
}
    
💥 3. Cache Avalanche (캐시 눈사태)

대량의 캐시가 동시에 만료되어 DB에 갑자기 엄청난 부하가 몰리는 현상이야. 서버 재시작 후 캐시가 비어있을 때 자주 발생해.


// 해결책: TTL에 랜덤 지터(Jitter) 추가
@Service
public class AvalancheProtectedService {
    
    private final Random random = new Random();
    
    // TTL에 랜덤 값 추가로 만료 시점 분산
    private Duration getJitteredTTL(long baseTtlMinutes) {
        // 기본 TTL ± 20% 랜덤 지터
        long jitter = (long) (baseTtlMinutes * 0.2 * (random.nextDouble() * 2 - 1));
        return Duration.ofMinutes(baseTtlMinutes + jitter);
    }
    
    public void cacheProduct(String key, Product product) {
        // 30분 ± 6분 랜덤 TTL
        Duration ttl = getJitteredTTL(30);
        redisTemplate.opsForValue().set(key, product, ttl);
    }
    
    // 캐시 워밍업 (서버 시작 시 미리 캐시 채우기)
    @EventListener(ApplicationReadyEvent.class)
    public void warmUpCache() {
        List<Product> popularProducts = productRepository.findTopPopular(1000);
        popularProducts.forEach(product -> {
            String key = "product:" + product.getId();
            cacheProduct(key, product);
        });
        System.out.println("캐시 워밍업 완료! " + popularProducts.size() + "개 상품 캐싱됨");
    }
}
    
✅ 캐시 워밍업(Cache Warming)은 서버 시작 직후 캐시가 비어있는 상태에서 발생하는 Cold Start 문제를 해결하는 핵심 기법이야. 인기 데이터를 미리 캐시에 올려두는 거지!

📊 캐시 모니터링과 성능 측정

캐시를 도입했으면 제대로 동작하는지 모니터링해야지! 히트율이 낮으면 캐시가 오히려 독이 될 수도 있어 ㅋㅋ

📈 Caffeine 캐시 통계 모니터링

// Micrometer와 연동한 캐시 메트릭 수집
@Configuration
public class CacheMetricsConfig {
    
    @Bean
    public CaffeineCache caffeineCache(MeterRegistry meterRegistry) {
        Cache<Object, Object> cache = Caffeine.newBuilder()
            .maximumSize(10000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .recordStats()  // 통계 수집 활성화 필수!
            .build();
        
        // Micrometer에 캐시 등록
        CaffeineStatsCounter statsCounter = new CaffeineStatsCounter(meterRegistry, "products");
        
        return new CaffeineCache("products", cache);
    }
}

// 캐시 통계 조회 서비스
@Service
@RequiredArgsConstructor
public class CacheMonitorService {
    
    private final CacheManager cacheManager;
    
    public Map<String, Object> getCacheStats(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache instanceof CaffeineCache) {
            com.github.benmanes.caffeine.cache.Cache<Object, Object> nativeCache = 
                ((CaffeineCache) cache).getNativeCache();
            CacheStats stats = nativeCache.stats();
            
            Map<String, Object> result = new HashMap<>();
            result.put("hitRate", String.format("%.2f%%", stats.hitRate() * 100));
            result.put("hitCount", stats.hitCount());
            result.put("missCount", stats.missCount());
            result.put("loadSuccessCount", stats.loadSuccessCount());
            result.put("averageLoadPenaltyMs", 
                stats.averageLoadPenalty() / 1_000_000.0);
            result.put("evictionCount", stats.evictionCount());
            result.put("estimatedSize", nativeCache.estimatedSize());
            
            return result;
        }
        return Collections.emptyMap();
    }
}

// 캐시 통계 API 엔드포인트
@RestController
@RequestMapping("/admin/cache")
@RequiredArgsConstructor
public class CacheAdminController {
    
    private final CacheMonitorService cacheMonitorService;
    private final CacheManager cacheManager;
    
    @GetMapping("/stats/{cacheName}")
    public ResponseEntity<Map<String, Object>> getCacheStats(
            @PathVariable String cacheName) {
        return ResponseEntity.ok(cacheMonitorService.getCacheStats(cacheName));
    }
    
    @DeleteMapping("/evict/{cacheName}")
    public ResponseEntity<String> evictCache(@PathVariable String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            cache.clear();
            return ResponseEntity.ok(cacheName + " 캐시 초기화 완료");
        }
        return ResponseEntity.notFound().build();
    }
}
    
📊 Redis 모니터링

// Redis INFO 명령어로 상태 확인
@Service
@RequiredArgsConstructor
public class RedisMonitorService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    public Map<String, String> getRedisInfo() {
        Properties info = redisTemplate.execute(
            (RedisCallback<Properties>) connection -> connection.serverCommands().info()
        );
        
        Map<String, String> result = new HashMap<>();
        if (info != null) {
            // 메모리 사용량
            result.put("usedMemory", info.getProperty("used_memory_human"));
            result.put("maxMemory", info.getProperty("maxmemory_human"));
            
            // 히트율
            String hits = info.getProperty("keyspace_hits");
            String misses = info.getProperty("keyspace_misses");
            if (hits != null && misses != null) {
                long h = Long.parseLong(hits);
                long m = Long.parseLong(misses);
                double hitRate = h + m > 0 ? (double) h / (h + m) * 100 : 0;
                result.put("hitRate", String.format("%.2f%%", hitRate));
            }
            
            // 연결 수
            result.put("connectedClients", info.getProperty("connected_clients"));
            
            // 초당 명령어 처리 수
            result.put("instantaneousOpsPerSec", 
                info.getProperty("instantaneous_ops_per_sec"));
        }
        
        return result;
    }
    
    // 키 개수 확인
    public Long getKeyCount() {
        return redisTemplate.execute(
            (RedisCallback<Long>) connection -> connection.serverCommands().dbSize()
        );
    }
    
    // 메모리 사용량 확인
    public Long getMemoryUsage(String key) {
        return redisTemplate.execute(
            (RedisCallback<Long>) connection -> 
                connection.keyCommands().memUsage(key.getBytes())
        );
    }
}
    
✅ Redis 히트율은 최소 80% 이상을 목표로 해야 해. 히트율이 50% 미만이면 캐시 키 설계나 TTL 설정을 재검토해야 할 신호야!

🎯 실전 캐싱 전략 - 상황별 베스트 프랙티스
🛒 이커머스 상품 캐싱 전략

@Service
@RequiredArgsConstructor
public class EcommerceProductService {
    
    // 상품 상세: 자주 조회, 가끔 변경 → 긴 TTL
    @Cacheable(value = "product-detail", key = "#id", 
               unless = "#result == null")
    public ProductDetailDto getProductDetail(Long id) {
        return productRepository.findDetailById(id);
    }
    
    // 상품 목록: 페이지네이션, 필터 조합 → 중간 TTL
    @Cacheable(value = "product-list", 
               key = "#category + ':' + #page + ':' + #size + ':' + #sort")
    public Page<ProductSummaryDto> getProductList(
            String category, int page, int size, String sort) {
        return productRepository.findByCategory(category, 
            PageRequest.of(page, size, Sort.by(sort)));
    }
    
    // 실시간 재고: 자주 변경 → 매우 짧은 TTL 또는 캐싱 안 함
    // @Cacheable(value = "stock", key = "#productId")  // 주석 처리 - 실시간 필요
    public int getStock(Long productId) {
        return inventoryRepository.getStock(productId);
    }
    
    // 인기 상품: 집계 쿼리 → 긴 TTL + 스케줄러로 갱신
    @Cacheable(value = "popular-products", key = "#category")
    public List<ProductSummaryDto> getPopularProducts(String category) {
        return productRepository.findTopByCategory(category, 20);
    }
    
    // 스케줄러로 인기 상품 캐시 주기적 갱신
    @Scheduled(fixedDelay = 3600000)  // 1시간마다
    @CacheEvict(value = "popular-products", allEntries = true)
    public void refreshPopularProductsCache() {
        System.out.println("인기 상품 캐시 갱신 완료");
    }
    
    // 상품 업데이트 시 관련 캐시 모두 무효화
    @Caching(evict = {
        @CacheEvict(value = "product-detail", key = "#product.id"),
        @CacheEvict(value = "product-list", allEntries = true),
        @CacheEvict(value = "popular-products", allEntries = true)
    })
    @CachePut(value = "product-detail", key = "#result.id")
    public ProductDetailDto updateProduct(ProductUpdateRequest product) {
        Product updated = productRepository.save(product.toEntity());
        return ProductDetailDto.from(updated);
    }
}
    
👤 사용자 세션 캐싱

// Spring Session + Redis 연동
// build.gradle: implementation 'org.springframework.session:spring-session-data-redis'

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)  // 1시간 세션
public class SessionConfig {
    // Spring Session이 자동으로 Redis에 세션 저장!
}

// 사용자 정보 캐싱 (세션과 별도)
@Service
public class UserCacheService {
    
    @Cacheable(value = "user-profile", key = "#userId")
    public UserProfileDto getUserProfile(Long userId) {
        return userRepository.findProfileById(userId);
    }
    
    // 권한 정보 캐싱 (보안상 짧은 TTL)
    @Cacheable(value = "user-permissions", key = "#userId")
    public Set<String> getUserPermissions(Long userId) {
        return permissionRepository.findByUserId(userId);
    }
    
    // 로그아웃 시 캐시 무효화
    @Caching(evict = {
        @CacheEvict(value = "user-profile", key = "#userId"),
        @CacheEvict(value = "user-permissions", key = "#userId")
    })
    public void logout(Long userId) {
        // 세션 무효화 로직
    }
}
    
🏆 실시간 랭킹 시스템 (Redis Sorted Set)

@Service
@RequiredArgsConstructor
public class RankingService {
    
    private final StringRedisTemplate redisTemplate;
    private static final String RANKING_KEY = "game:ranking";
    
    // 점수 업데이트
    public void updateScore(String userId, double score) {
        redisTemplate.opsForZSet().add(RANKING_KEY, userId, score);
    }
    
    // 점수 증가
    public Double incrementScore(String userId, double delta) {
        return redisTemplate.opsForZSet()
            .incrementScore(RANKING_KEY, userId, delta);
    }
    
    // 상위 N명 조회 (내림차순)
    public List<RankingEntry> getTopRanking(int count) {
        Set<ZSetOperations.TypedTuple<String>> topUsers = 
            redisTemplate.opsForZSet()
                .reverseRangeWithScores(RANKING_KEY, 0, count - 1);
        
        List<RankingEntry> result = new ArrayList<>();
        int rank = 1;
        for (ZSetOperations.TypedTuple<String> tuple : topUsers) {
            result.add(new RankingEntry(rank++, tuple.getValue(), tuple.getScore()));
        }
        return result;
    }
    
    // 특정 유저 순위 조회
    public Long getUserRank(String userId) {
        Long rank = redisTemplate.opsForZSet()
            .reverseRank(RANKING_KEY, userId);
        return rank != null ? rank + 1 : null;  // 0-based → 1-based
    }
    
    // 특정 유저 점수 조회
    public Double getUserScore(String userId) {
        return redisTemplate.opsForZSet().score(RANKING_KEY, userId);
    }
    
    // 주변 순위 조회 (내 순위 ± 5명)
    public List<RankingEntry> getSurroundingRanking(String userId) {
        Long myRank = redisTemplate.opsForZSet()
            .reverseRank(RANKING_KEY, userId);
        if (myRank == null) return Collections.emptyList();
        
        long start = Math.max(0, myRank - 5);
        long end = myRank + 5;
        
        Set<ZSetOperations.TypedTuple<String>> surrounding = 
            redisTemplate.opsForZSet()
                .reverseRangeWithScores(RANKING_KEY, start, end);
        
        List<RankingEntry> result = new ArrayList<>();
        long rank = start + 1;
        for (ZSetOperations.TypedTuple<String> tuple : surrounding) {
            result.add(new RankingEntry(rank++, tuple.getValue(), tuple.getScore()));
        }
        return result;
    }
}
    
✅ Redis Sorted Set을 이용한 랭킹 시스템은 O(log N) 시간 복잡도로 동작해. 100만 명의 랭킹도 실시간으로 처리 가능! 재능넷 같은 플랫폼에서 재능 판매자 랭킹 시스템 구현에도 딱이야 😄

🔧 캐시 직렬화 - 놓치면 안 되는 핵심

Redis에 Java 객체를 저장할 때 직렬화(Serialization)가 필요해. 잘못 설정하면 성능 저하, 호환성 문제, 보안 취약점이 생길 수 있어. 이거 진짜 중요한데 많이들 대충 넘어가더라 ㅋㅋ

📦 직렬화 방식 비교
직렬화 방식 장점 단점 권장 여부
JDK 기본 직렬화 별도 설정 불필요 크기 큼, 보안 취약, 클래스 변경 시 호환성 문제 ❌ 비권장
JSON (Jackson) 사람이 읽기 쉬움, 언어 독립적 JDK 직렬화보다 약간 느림 ✅ 권장
Kryo 매우 빠름, 크기 작음 Java 전용, 설정 복잡 ⚡ 고성능 필요 시
Protobuf 가장 빠름, 크기 가장 작음 스키마 정의 필요, 복잡 ⚡ 극한 최적화 시

// 권장: GenericJackson2JsonRedisSerializer 사용
@Bean
public RedisTemplate<String, Object> redisTemplate(
        RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    
    // ObjectMapper 커스터마이징
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.activateDefaultTyping(
        LaissezFaireSubTypeValidator.instance,
        ObjectMapper.DefaultTyping.NON_FINAL,
        JsonTypeInfo.As.PROPERTY
    );
    objectMapper.registerModule(new JavaTimeModule());  // LocalDateTime 지원
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    
    GenericJackson2JsonRedisSerializer serializer = 
        new GenericJackson2JsonRedisSerializer(objectMapper);
    
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(serializer);
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(serializer);
    template.afterPropertiesSet();
    
    return template;
}

// 캐시 대상 클래스는 반드시 직렬화 가능하게!
@Getter
@NoArgsConstructor  // 역직렬화를 위한 기본 생성자 필수!
@AllArgsConstructor
public class ProductDetailDto implements Serializable {
    private static final long serialVersionUID = 1L;  // 버전 관리
    
    private Long id;
    private String name;
    private BigDecimal price;
    private LocalDateTime createdAt;
    // ...
}
    
⚠️ Jackson 직렬화 시 @class 타입 정보가 JSON에 포함돼. 클래스 패키지 경로가 바뀌면 역직렬화 실패! 클래스 리팩토링 시 반드시 캐시 초기화 필요.

⚡ 성능 벤치마크 - 숫자로 보는 캐싱 효과

말로만 하면 믿기 어려우니까 실제 수치로 보여줄게. 이 정도면 캐싱 안 쓸 이유가 없지 ㅋㅋ

응답 시간 비교 벤치마크 100ms 75ms 50ms 25ms 0ms ~100ms DB 직접 ~0.1ms Caffeine ~1ms Redis ~0.5ms Hazelcast ~0.05ms 멀티레이어 * 단순 키-값 조회 기준, 네트워크 환경에 따라 다를 수 있음
캐시 방식 평균 응답 시간 초당 처리량(TPS) 메모리 사용
DB 직접 조회 50~200ms ~1,000 TPS DB 서버 부하
Caffeine 로컬 캐시 0.05~0.5ms ~10,000,000 TPS JVM 힙 메모리
Redis (로컬 네트워크) 0.5~2ms ~100,000 TPS Redis 서버 메모리
Hazelcast 임베디드 0.1~1ms ~1,000,000 TPS JVM 힙 메모리
멀티레이어 (L1+L2) 0.05~0.5ms (L1 히트 시) ~10,000,000 TPS (L1 히트 시) JVM + Redis 분산

🎓 캐싱 설계 원칙 - 이것만 기억해!

캐싱은 강력하지만 잘못 쓰면 오히려 독이 돼. 재능넷에서 다양한 개발 재능을 가진 분들이 공유하는 노하우처럼, 아래 원칙들은 수많은 실전 경험에서 나온 거야 😊

1
캐시 키 설계를 신중하게
키는 고유하고 예측 가능해야 해. 네임스페이스를 사용해서 충돌을 방지해. 예: service:entity:id:version
2
TTL은 데이터 특성에 맞게
실시간 데이터(재고, 가격): 짧은 TTL 또는 캐싱 안 함. 정적 데이터(카테고리, 설정): 긴 TTL. 사용자 데이터: 중간 TTL.
3
캐시 무효화 전략을 명확히
데이터 변경 시 캐시를 어떻게 무효화할지 미리 설계해야 해. "캐시 무효화는 컴퓨터 과학에서 가장 어려운 문제 중 하나"라는 말이 있을 정도야 ㅋㅋ
4
히트율을 지속적으로 모니터링
히트율이 80% 미만이면 캐시 전략을 재검토해. 캐시가 오히려 복잡성만 추가하는 상황일 수 있어.
5
캐시 없이도 동작해야 함
Redis 서버가 다운되어도 서비스가 동작해야 해. 캐시는 성능 향상을 위한 것이지, 필수 인프라가 되면 안 돼. Circuit Breaker 패턴을 함께 사용해!
6
캐시 크기 제한 설정
메모리는 유한해. maximumSize나 maxmemory를 반드시 설정하고, 적절한 Eviction Policy(LRU, LFU 등)를 선택해.
7
민감한 데이터 캐싱 주의
개인정보, 결제 정보 등은 캐싱 시 보안에 특히 주의해야 해. 암호화 저장 또는 캐싱 자체를 피하는 것이 좋아.
💡 캐싱의 황금률: "측정하지 않은 최적화는 최적화가 아니다!" 캐시 도입 전후의 성능을 반드시 측정하고, 히트율·응답시간·DB 부하를 지속적으로 모니터링해야 해.

🚀 마무리 - 캐싱 마스터로 가는 길

자, 여기까지 자바 캐싱의 기초부터 Redis, Hazelcast를 활용한 고급 전략까지 쭉 달려왔어! 정리하면:

✅
로컬 캐시(Caffeine): 단일 서버, 초고속, 분산 환경에서는 일관성 문제 주의
✅
Redis: 분산 환경 표준, 다양한 데이터 구조, 성숙한 생태계, 별도 서버 필요
✅
Hazelcast: Java 네이티브, 임베디드 가능, 자동 클러스터링, 분산 연산 강점
✅
멀티레이어: L1(로컬) + L2(분산) 조합으로 최고 성능 달성
✅
Spring Cache Abstraction: 어노테이션으로 간편하게, 구현체 교체 용이


캐싱은 한 번 배워두면 어떤 프로젝트에서든 써먹을 수 있는 핵심 스킬이야. 처음엔 복잡해 보여도 하나씩 적용해보면서 감을 잡아봐! 실제로 캐시 히트율이 올라가고 응답 시간이 줄어드는 걸 보면 진짜 뿌듯하거든 ㅋㅋ

더 깊은 내용이나 실전 프로젝트에서의 캐싱 전략이 궁금하다면, 재능넷에서 Java 백엔드 전문가들의 재능을 활용해보는 것도 좋은 방법이야! 다양한 실전 경험을 가진 개발자들이 1:1로 도움을 줄 수 있거든 😊

댓글 작성

이 글에 대한 여러분의 생각을 들려주세요

댓글 0
댓글을 불러오는 중입니다.

아직 댓글이 없습니다.