|
| 1 | +package com.loopers.support.cache; |
| 2 | + |
| 3 | +import com.loopers.support.page.PageWrapper; |
| 4 | +import java.time.Duration; |
| 5 | +import java.util.function.Supplier; |
| 6 | +import lombok.RequiredArgsConstructor; |
| 7 | +import org.springframework.data.domain.Page; |
| 8 | +import org.springframework.data.redis.core.RedisTemplate; |
| 9 | +import org.springframework.stereotype.Component; |
| 10 | + |
| 11 | +@RequiredArgsConstructor |
| 12 | +@Component |
| 13 | +public class RedisCacheHandler { |
| 14 | + private final RedisTemplate<String, Object> redisTemplate; |
| 15 | + |
| 16 | + /** |
| 17 | + * 캐시 조회 -> (없거나 에러나면) -> DB 조회 -> 캐시 저장 |
| 18 | + * @param key 캐시 키 |
| 19 | + * @param ttl 만료 시간 |
| 20 | + * @param type 반환 타입 (캐스팅용) |
| 21 | + * @param dbFetcher DB 조회 로직 (람다) |
| 22 | + */ |
| 23 | + public <T> T getOrLoad(String key, Duration ttl, Class<T> type, Supplier<T> dbFetcher) { |
| 24 | + try { |
| 25 | + Object cachedData = redisTemplate.opsForValue().get(key); |
| 26 | + if (cachedData != null) { |
| 27 | + |
| 28 | + if (cachedData instanceof PageWrapper) { |
| 29 | + return (T) ((PageWrapper<?>) cachedData).toPage(); |
| 30 | + } |
| 31 | + return type.cast(cachedData); |
| 32 | + } |
| 33 | + } catch (Exception e) { |
| 34 | + } |
| 35 | + |
| 36 | + T result = dbFetcher.get(); |
| 37 | + |
| 38 | + if (result != null) { |
| 39 | + try { |
| 40 | + Object dataToSave = result; |
| 41 | + if (result instanceof Page) { |
| 42 | + dataToSave = new PageWrapper<>((Page<?>) result); |
| 43 | + } |
| 44 | + |
| 45 | + redisTemplate.opsForValue().set(key, dataToSave, ttl); |
| 46 | + } catch (Exception e) { |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return result; |
| 51 | + } |
| 52 | +} |
0 commit comments