Skip to content

Commit

Permalink
fix: 분산락 오류 수정 (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
gengminy authored Dec 21, 2023
1 parent 528066e commit 51b3041
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
Expand All @@ -21,22 +22,24 @@
@Component
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
@Order(Ordered.LOWEST_PRECEDENCE - 1)
public class DistributedLockAop {
private final LockManager lockManager;

@Around("@annotation(distributedLock)")
public void lock(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) {
public Object lock(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) {
final String key = createDynamicKey(joinPoint, distributedLock);
lockManager.lock(
key,
() -> {
try {
return joinPoint.proceed();
} catch (Throwable throwable) {
throw new InvalidLockException("Lock Error", throwable);
}
});
return lockManager.lock(key, () -> proceed(joinPoint));
}

@SneakyThrows
private Object proceed(ProceedingJoinPoint joinPoint) {
try {
return joinPoint.proceed();
} catch (Throwable e) {
log.error("Error during proceeding joinPoint", e);
throw e;
}
}

private String createDynamicKey(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class NamedLockManager implements LockManager {
private static final String RELEASE_LOCK = "SELECT RELEASE_LOCK(?)";
private static final String NULL_EXCEPTION = "잘못된 인자입니다.";
private static final String EMPTY_EXCEPTION = "잘못된 키값입니다.";
private static final int TIMEOUT_SECONDS = 10;
private static final int TIMEOUT_SECONDS = 5;
private final DataSource dataSource;

@Transactional(propagation = Propagation.NEVER)
Expand All @@ -34,27 +34,26 @@ public <T> T lock(String userLockName, Supplier<T> supplier) {
} finally {
releaseLock(connection, userLockName);
}
} catch (SQLException | RuntimeException e) {
} catch (SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}

private void getLock(Connection connection, String userLockName) {

private void getLock(Connection connection, String lockName) {
try (PreparedStatement preparedStatement = connection.prepareStatement(GET_LOCK)) {
preparedStatement.setString(1, userLockName);
preparedStatement.setString(1, lockName);
preparedStatement.setInt(2, TIMEOUT_SECONDS);

validateLockStatement(preparedStatement);
} catch (SQLException e) {
log.error("releaseLock Error", e);
log.error("getLock Error", e);
throw new InvalidLockException(e.getMessage(), e);
}
}

private void releaseLock(Connection connection, String userLockName) {
private void releaseLock(Connection connection, String lockName) {
try (PreparedStatement preparedStatement = connection.prepareStatement(RELEASE_LOCK)) {
preparedStatement.setString(1, userLockName);
preparedStatement.setString(1, lockName);

validateLockStatement(preparedStatement);
} catch (SQLException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public CarReservationResponse postCarReservation(
@AuthMember Member member, @Valid @RequestBody CarReservationRequest request) {
final CarReservation carReservation =
carReservationService.reserve(member, request.getCarStockId());

System.out.println("carReservation = " + carReservation);
return CarReservationResponse.from(carReservation);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,12 @@ public List<CarReservationCountVo> findAllByLast7DaysRank() {
}

/** 시험차량을 예약합니다. */
@DistributedLock(type = DistributedLockType.TRACK, identifier = "carStockId")
@DistributedLock(type = DistributedLockType.CAR, identifier = "carStockId")
public CarReservation reserve(Member member, Long carStockId) {
final CarStock carStock = carStockService.findById(carStockId);
validateCarStockAvailable(carStock);
carStock.updateStatus(StockStatus.RESERVED);
carStockRepository.save(carStock);
final LocalDateTime now = LocalDateTime.now();
final LocalDateTime expiredAt = now.toLocalDate().plusDays(RESERVATION_DATE).atStartOfDay();
final CarReservation carReservation =
Expand All @@ -89,8 +91,6 @@ public CarReservation reserve(Member member, Long carStockId) {
.startedAt(now)
.expiredAt(expiredAt)
.build();
carStock.updateStatus(StockStatus.RESERVED);
carStockRepository.save(carStock);
return carReservationRepository.save(carReservation);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Getter
@ToString
@Entity
@Table(name = "CarReservation")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.testcar.car.domains.carReservation.entity.CarReservation;
import com.testcar.car.domains.carReservation.entity.ReservationStatus;
import com.testcar.car.domains.carReservation.model.dto.CarReservationDto;
import com.testcar.car.domains.carStock.entity.CarStock;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.Builder;
Expand Down Expand Up @@ -46,12 +45,10 @@ public static CarReservationResponse from(CarReservationDto carReservationDto) {
}

public static CarReservationResponse from(CarReservation carReservation) {
final CarStock carStock = carReservation.getCarStock();

return CarReservationResponse.builder()
.id(carReservation.getId())
.name(carStock.getCar().getName())
.stockNumber(carStock.getStockNumber())
.name(carReservation.getCarStock().getCar().getName())
.stockNumber(carReservation.getCarStock().getStockNumber())
.startedAt(carReservation.getStartedAt())
.expiredAt(carReservation.getExpiredAt())
.status(carReservation.getStatus())
Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ spring:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
generate-ddl: false
show-sql: false
show-sql: true
properties:
hibernate:
format_sql: false
format_sql: true
flyway:
enabled: true
baseline-on-migrate: true
Expand Down

0 comments on commit 51b3041

Please sign in to comment.