-
Notifications
You must be signed in to change notification settings - Fork 0
[REFACTOR] 알림 조회 redis 캐싱 추가 #404
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+113
−3
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
95 changes: 95 additions & 0 deletions
95
...com/example/RealMatch/notification/infrastructure/redis/NotificationUnreadCountCache.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| package com.example.RealMatch.notification.infrastructure.redis; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.OptionalLong; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.data.redis.core.StringRedisTemplate; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.support.TransactionSynchronization; | ||
| import org.springframework.transaction.support.TransactionSynchronizationManager; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| /** | ||
| * 미읽음 알림 개수 조회 성능 최적화를 위한 Redis 캐시. | ||
| * <p>캐시 키: notification:unread:{userId} | ||
| * <p>캐시 무효화: 알림 생성, 읽음 처리, 전체 읽기, 소프트 삭제 시 호출 | ||
| * <p>Redis 장애 시 DB 조회로 폴백 | ||
| */ | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class NotificationUnreadCountCache { | ||
|
|
||
| private static final Logger LOG = LoggerFactory.getLogger(NotificationUnreadCountCache.class); | ||
| private static final String KEY_PREFIX = "notification:unread:"; | ||
| private static final Duration TTL = Duration.ofMinutes(10); | ||
|
|
||
| private final StringRedisTemplate redisTemplate; | ||
|
|
||
| public OptionalLong get(Long userId) { | ||
| if (userId == null) { | ||
| return OptionalLong.empty(); | ||
| } | ||
| try { | ||
| String key = KEY_PREFIX + userId; | ||
| String value = redisTemplate.opsForValue().get(key); | ||
| if (value == null) { | ||
| return OptionalLong.empty(); | ||
| } | ||
| return OptionalLong.of(Long.parseLong(value)); | ||
| } catch (NumberFormatException e) { | ||
| invalidate(userId); | ||
| return OptionalLong.empty(); | ||
1000hyehyang marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } catch (Exception e) { | ||
| LOG.warn("[UnreadCountCache] Redis get failed, fallback to DB. userId={}", userId, e); | ||
| return OptionalLong.empty(); | ||
| } | ||
| } | ||
|
|
||
| public void set(Long userId, long count) { | ||
| if (userId == null) { | ||
| return; | ||
| } | ||
| try { | ||
| redisTemplate.opsForValue().set(KEY_PREFIX + userId, String.valueOf(count), TTL); | ||
| } catch (Exception e) { | ||
| LOG.warn("[UnreadCountCache] Redis set failed. userId={}", userId, e); | ||
| } | ||
| } | ||
|
|
||
| public void invalidate(Long userId) { | ||
| if (userId == null) { | ||
| return; | ||
| } | ||
| try { | ||
| redisTemplate.delete(KEY_PREFIX + userId); | ||
| } catch (Exception e) { | ||
| LOG.warn("[UnreadCountCache] Redis invalidate failed. userId={}", userId, e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * 트랜잭션 커밋 완료 후 캐시를 무효화합니다. | ||
| * <p>커밋 이전 무효화 시 다른 스레드가 아직 커밋되지 않은 DB 값을 읽어 | ||
| * 캐시에 저장하는 레이스 컨디션을 방지합니다. | ||
| */ | ||
| public void invalidateAfterCommit(Long userId) { | ||
| if (userId == null) { | ||
| return; | ||
| } | ||
| if (TransactionSynchronizationManager.isSynchronizationActive()) { | ||
| TransactionSynchronizationManager.registerSynchronization( | ||
| new TransactionSynchronization() { | ||
| @Override | ||
| public void afterCommit() { | ||
| invalidate(userId); | ||
| } | ||
| } | ||
1000hyehyang marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ); | ||
| } else { | ||
| invalidate(userId); | ||
| } | ||
1000hyehyang marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.