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

자바 캐싱과 Redis·Hazelcast를 활용한 성능 최적화
솔직히 말하면, 캐싱은 개발자들 사이에서 "성능 문제의 80%를 해결하는 마법"이라고 불릴 정도야. 근데 막상 제대로 이해하고 쓰는 사람은 생각보다 많지 않음 ㅋㅋ
캐싱(Caching)이란 자주 사용되는 데이터를 빠른 저장소에 미리 저장해두고, 같은 요청이 오면 원본 소스(DB, API 등)에 다시 접근하지 않고 저장된 데이터를 바로 돌려주는 기법이야.
예를 들어볼게. 네가 매일 아침 편의점에서 같은 삼각김밥을 사는데, 편의점 직원이 매번 창고에서 꺼내온다면? 시간 낭비잖아. 근데 카운터 앞에 미리 꺼내놓으면? 바로 집어갈 수 있지. 이게 바로 캐싱의 개념이야 😄
아래 상황 중 하나라도 해당되면 캐싱을 진지하게 고려해야 해:
예: 메인 페이지 배너 데이터, 카테고리 목록, 공지사항 등 자주 바뀌지 않는 데이터
예: 날씨 API, 환율 API, 지도 API 등 실시간성이 크게 중요하지 않은 경우
예: 통계 집계, 추천 알고리즘 결과, 복잡한 비즈니스 로직 계산값
예: 이벤트, 세일, 뉴스 기사 바이럴 등 특정 시점에 동일 데이터 요청이 폭발적으로 증가
처음엔 다들 이렇게 시작해. 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(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);
}
}
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());
}
}
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);
}
}
Redis(Remote Dictionary Server)는 인메모리 데이터 구조 저장소야. 2009년 Salvatore Sanfilippo가 만들었고, 현재 전 세계에서 가장 많이 사용되는 캐시 솔루션이야. 왜 이렇게 인기 있냐고? 이유가 있지 ㅋㅋ
// 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을 직접 사용하면 더 세밀한 제어가 가능해:
@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);
}
}
}
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는 Java 기반의 오픈소스 인메모리 데이터 그리드(IMDG)야. Redis와 달리 JVM 프로세스 내부에 임베디드로 실행할 수 있어서 네트워크 오버헤드가 없다는 게 큰 장점이야. 물론 클라이언트-서버 모드도 지원해.
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);
}
}
@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);
}
}
이게 진짜 많이 물어보는 질문이야. 정답은 없고 상황에 따라 다른데, 아래 비교표를 보면 선택이 쉬워질 거야 ㅋㅋ
| 비교 항목 | 🔴 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 (오픈소스) |
실제 대규모 서비스에서는 로컬 캐시 + 분산 캐시를 함께 사용하는 멀티레이어 캐싱을 써. 이걸 L1/L2 캐시라고도 부르는데, 각 레이어의 장점을 극대화하는 방식이야.
@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);
}
}
}
캐시가 만료되는 순간 수천 개의 요청이 동시에 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); // 재귀 호출
}
}
}
존재하지 않는 키로 계속 요청이 들어와서 캐시를 우회하고 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);
}
}
대량의 캐시가 동시에 만료되어 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() + "개 상품 캐싱됨");
}
}
캐시를 도입했으면 제대로 동작하는지 모니터링해야지! 히트율이 낮으면 캐시가 오히려 독이 될 수도 있어 ㅋㅋ
// 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 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())
);
}
}
@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) {
// 세션 무효화 로직
}
}
@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에 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;
// ...
}
말로만 하면 믿기 어려우니까 실제 수치로 보여줄게. 이 정도면 캐싱 안 쓸 이유가 없지 ㅋㅋ
| 캐시 방식 | 평균 응답 시간 | 초당 처리량(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 분산 |
캐싱은 강력하지만 잘못 쓰면 오히려 독이 돼. 재능넷에서 다양한 개발 재능을 가진 분들이 공유하는 노하우처럼, 아래 원칙들은 수많은 실전 경험에서 나온 거야 😊
키는 고유하고 예측 가능해야 해. 네임스페이스를 사용해서 충돌을 방지해. 예:
service:entity:id:version실시간 데이터(재고, 가격): 짧은 TTL 또는 캐싱 안 함. 정적 데이터(카테고리, 설정): 긴 TTL. 사용자 데이터: 중간 TTL.
데이터 변경 시 캐시를 어떻게 무효화할지 미리 설계해야 해. "캐시 무효화는 컴퓨터 과학에서 가장 어려운 문제 중 하나"라는 말이 있을 정도야 ㅋㅋ
히트율이 80% 미만이면 캐시 전략을 재검토해. 캐시가 오히려 복잡성만 추가하는 상황일 수 있어.
Redis 서버가 다운되어도 서비스가 동작해야 해. 캐시는 성능 향상을 위한 것이지, 필수 인프라가 되면 안 돼. Circuit Breaker 패턴을 함께 사용해!
메모리는 유한해. maximumSize나 maxmemory를 반드시 설정하고, 적절한 Eviction Policy(LRU, LFU 등)를 선택해.
개인정보, 결제 정보 등은 캐싱 시 보안에 특히 주의해야 해. 암호화 저장 또는 캐싱 자체를 피하는 것이 좋아.
자, 여기까지 자바 캐싱의 기초부터 Redis, Hazelcast를 활용한 고급 전략까지 쭉 달려왔어! 정리하면:
캐싱은 한 번 배워두면 어떤 프로젝트에서든 써먹을 수 있는 핵심 스킬이야. 처음엔 복잡해 보여도 하나씩 적용해보면서 감을 잡아봐! 실제로 캐시 히트율이 올라가고 응답 시간이 줄어드는 걸 보면 진짜 뿌듯하거든 ㅋㅋ
더 깊은 내용이나 실전 프로젝트에서의 캐싱 전략이 궁금하다면, 재능넷에서 Java 백엔드 전문가들의 재능을 활용해보는 것도 좋은 방법이야! 다양한 실전 경험을 가진 개발자들이 1:1로 도움을 줄 수 있거든 😊
댓글 작성
이 글에 대한 여러분의 생각을 들려주세요
로그인이 필요합니다
댓글을 작성하려면 먼저 로그인해주세요.
댓글 0
지식인의 숲 - 지적 재산권 보호 고지
지적 재산권 보호 고지
- 저작권 및 소유권: 본 컨텐츠는 재능넷의 독점 AI 기술로 생성되었으며, 대한민국 저작권법 및 국제 저작권 협약에 의해 보호됩니다.
- AI 생성 컨텐츠의 법적 지위: 본 AI 생성 컨텐츠는 재능넷의 지적 창작물로 인정되며, 관련 법규에 따라 저작권 보호를 받습니다.
- 사용 제한: 재능넷의 명시적 서면 동의 없이 본 컨텐츠를 복제, 수정, 배포, 또는 상업적으로 활용하는 행위는 엄격히 금지됩니다.
- 데이터 수집 금지: 본 컨텐츠에 대한 무단 스크래핑, 크롤링, 및 자동화된 데이터 수집은 법적 제재의 대상이 됩니다.
- AI 학습 제한: 재능넷의 AI 생성 컨텐츠를 타 AI 모델 학습에 무단 사용하는 행위는 금지되며, 이는 지적 재산권 침해로 간주됩니다.
아직 댓글이 없습니다.