데이터에 version 컬럼을 두고, UPDATE 시 version까지 같이 조건으로 걸어서
다른 트랜잭션이 먼저 수정했으면 업데이트 실패하게 만드는 방식
락을 잡지 않고 충돌을 감지하여
고성능·대량 트래픽에 유리하다
import lombok.RequiredArgsConstructor;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class PointsService {
private final PointsAccountRepository repository;
private static final int MAX_RETRY = 3;
public void charge(Long accountId, long amount) {
int retry = 0;
while (true) {
try {
chargeTx(accountId, amount);
return;
} catch (OptimisticLockingFailureException e) {
if (++retry >= MAX_RETRY) {
throw e;
}
}
}
}
@Transactional
protected void chargeTx(Long accountId, long amount) {
PointsAccount account = repository.findById(accountId)
.orElseThrow(() -> new IllegalArgumentException("계좌 없음"));
account.charge(amount);
//commit 시점에 version 체크
}
}'Etc' 카테고리의 다른 글
| AI Agent란 (0) | 2026.03.01 |
|---|---|
| LLM이란 (0) | 2026.02.22 |
| Lock에 대해서 (0) | 2026.01.25 |
| 검색형 ai 도구 - Perplexity (0) | 2026.01.25 |
| 코드가드 가 뭐지? (1) | 2026.01.18 |