-
Notifications
You must be signed in to change notification settings - Fork 0
쿠폰, 알림 수정 #109
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
쿠폰, 알림 수정 #109
Changes from all commits
Commits
Show all changes
3 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
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
78 changes: 78 additions & 0 deletions
78
src/main/java/com/catchtable/coupon/scheduler/CouponStockSyncScheduler.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,78 @@ | ||
| package com.catchtable.coupon.scheduler; | ||
|
|
||
| import com.catchtable.coupon.entity.CouponTemplate; | ||
| import com.catchtable.coupon.redis.RedisCouponIssuer; | ||
| import com.catchtable.coupon.repository.CouponTemplateRepository; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.redisson.api.RLock; | ||
| import org.redisson.api.RedissonClient; | ||
| import org.springframework.scheduling.annotation.Scheduled; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.support.TransactionTemplate; | ||
|
|
||
| import java.time.LocalDateTime; | ||
| import java.util.List; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| /** | ||
| * Redis stock → DB coupon_templates.remain 주기 동기화. | ||
| * | ||
| * 발급은 Redis 가 단일 진실원이라 DB remain 을 건드리지 않는다. 관리/통계 조회와 | ||
| * Redis 콜드 스타트 워밍업이 보는 DB 값을 Redis 와 맞추기 위해 본 잡이 sync. | ||
| * | ||
| * 함정: | ||
| * - Redis 키 만료/소실 시(stock == null) DB 를 0 으로 덮지 않는다. 워밍업이 | ||
| * DB remain 으로 Redis 를 다시 채우는 책임을 가지므로 0 으로 덮으면 정합성이 깨진다. | ||
| * - 메서드에 @Transactional 을 걸지 않는다. 루프 안의 Redis I/O 동안 DB 커넥션이 | ||
| * 점유되어 HikariCP 풀이 압박을 받는다. UPDATE 가 필요한 템플릿만 좁게 묶는다. | ||
| */ | ||
| @Slf4j | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class CouponStockSyncScheduler { | ||
|
|
||
| private static final long SYNC_INTERVAL_MS = 5_000L; | ||
| private static final String SYNC_LOCK_KEY = "lock:coupon:sync"; | ||
| private static final long LOCK_LEASE_SECONDS = 4L; | ||
|
|
||
| private final CouponTemplateRepository couponTemplateRepository; | ||
| private final RedisCouponIssuer redisCouponIssuer; | ||
| private final RedissonClient redissonClient; | ||
| private final TransactionTemplate transactionTemplate; | ||
|
|
||
| @Scheduled(fixedDelay = SYNC_INTERVAL_MS) | ||
| public void syncStock() { | ||
| RLock lock = redissonClient.getLock(SYNC_LOCK_KEY); | ||
| boolean acquired = false; | ||
| try { | ||
| acquired = lock.tryLock(0, LOCK_LEASE_SECONDS, TimeUnit.SECONDS); | ||
| if (!acquired) return; | ||
| doSync(); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| log.warn("쿠폰 stock sync 락 획득 인터럽트", e); | ||
| } finally { | ||
| if (acquired && lock.isHeldByCurrentThread()) { | ||
| lock.unlock(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private void doSync() { | ||
| List<CouponTemplate> templates = couponTemplateRepository.findActiveTemplates(LocalDateTime.now()); | ||
| for (CouponTemplate template : templates) { | ||
| try { | ||
| Integer stock = redisCouponIssuer.getStock(template.getId()); | ||
| if (stock == null) continue; | ||
| if (stock.equals(template.getRemain())) continue; | ||
| transactionTemplate.executeWithoutResult(status -> | ||
| couponTemplateRepository.findById(template.getId()) | ||
| .ifPresent(t -> t.syncRemain(stock)) | ||
| ); | ||
| } catch (Exception e) { | ||
| log.warn("쿠폰 stock sync 실패. templateId={}", template.getId(), e); | ||
| } | ||
| } | ||
| } | ||
| } | ||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이슈 및 개선 포인트:
본 스케줄러는 실서비스 환경(다중 인스턴스/멀티 포드)에서 운영될 때 두 가지 중요한 잠재적 문제를 가지고 있습니다.
@Transactional이syncStock()메서드 전체에 걸려 있어, 루프 내부에서 Redis 네트워크 I/O(redisCouponIssuer.getStock())를 호출하는 동안 DB 커넥션을 계속 점유하게 됩니다. Redis 지연이 발생하면 HikariCP 커넥션 풀이 빠르게 고갈될 수 있습니다.스케줄러가 각 인스턴스마다 5초 주기로 동시에 실행되어 불필요한 DB 조회 및 업데이트 경쟁(Lock Contention)을 유발합니다.
해결 방안:
@Transactional을 메서드 레벨에서 제거하고, 실제 DB 업데이트가 필요한 시점에만TransactionTemplate을 사용하여 트랜잭션 범위를 최소화합니다.RedissonClient를 활용하여 분산 락(Distributed Lock)을 적용함으로써, 다중 서버 환경에서도 단 하나의 인스턴스만 동기화 작업을 수행하도록 보장합니다.