
분산 환경에서 동시에 여러 프로세스가 동일한 리소스에 접근하는 문제를 방지하기 위해 사용
✅ 분산 락
✅ Redis lock 장점
Redis를 사용하여 Java에서 분산 락 및 다양한 동기화 기법을 지원하는 라이브러리
✅ Redisson의 기능
Redisson을 활용한 Redis Lock 사용법의존성 설정
dependencies {
implementation 'org.redisson:redisson-spring-boot-starter:3.16.3'
}
EX) 쿠폰발급시 redis lock적용
🔹 3-1. issueCoupon() - Redisson을 활용한 Redis 락 적용
@Transactional
public Coupon issueCoupon(CouponDto.IssueRequest request) {
String quantityKey = COUPON_QUANTITY_KEY + request.getCouponPolicyId();
String lockKey = COUPON_LOCK_KEY + request.getCouponPolicyId();
RLock lock = redissonClient.getLock(lockKey);
✅ RLock lock = redissonClient.getLock(lockKey);
🔹 3-2. 락 획득 시도
boolean isLocked = lock.tryLock(LOCK_WAIT_TIME, LOCK_LEASE_TIME, TimeUnit.SECONDS);
if (!isLocked) {
throw new CouponIssueException("쿠폰 발급 요청이 많아 처리할 수 없습니다. 잠시 후 다시 시도해주세요.");
}
✅ lock.tryLock(LOCK_WAIT_TIME, LOCK_LEASE_TIME, TimeUnit.SECONDS);
LOCK_WAIT_TIME 초 동안 대기하여 획득을 시도.LOCK_LEASE_TIME 초 동안 유지됨 (이후 자동 해제).→ 락이 없으면 락을 획득하여 쿠폰 발급을 진행하고, 락이 이미 걸려 있다면 예외를 던져 대기
🔹 3-3. 쿠폰 발급 로직 실행
CouponPolicy couponPolicy = couponPolicyService.getCouponPolicy(request.getCouponPolicyId());
LocalDateTime now = LocalDateTime.now();
if (now.isBefore(couponPolicy.getStartTime()) || now.isAfter(couponPolicy.getEndTime())) {
throw new IllegalStateException("쿠폰 발급 기간이 아닙니다.");
}
CouponPolicy)를 가져온 후, 쿠폰 발급 가능한 기간인지 검증.🔹 3-4. Redis를 이용한 쿠폰 수량 관리
RAtomicLong atomicQuantity = redissonClient.getAtomicLong(quantityKey);
long remainingQuantity = atomicQuantity.decrementAndGet();
if (remainingQuantity < 0) {
atomicQuantity.incrementAndGet();
throw new CouponIssueException("쿠폰이 모두 소진되었습니다.");
}
✅ Redis의 RAtomicLong을 사용하여 수량을 원자적으로 감소시킴
atomicQuantity.decrementAndGet() → 현재 쿠폰 수량을 감소시킴→ MySQL 트랜잭션을 사용하지 않고도 Redis에서 초고속으로 동시성을 관리
🔹 3-5. 쿠폰 저장 및 락 해제
return couponRepository.save(Coupon.builder()
.couponPolicy(couponPolicy)
.userId(UserIdInterceptor.getCurrentUserId())
.couponCode(generateCouponCode())
.build());
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
✅ lock.unlock();
finally 블록에서 락을 해제하여 무조건 락이 풀리도록 보장.