Replies: 2 comments
-
DB 자원 충돌을 해결하기 위해 락을 거는 방법을 고려할 수 있다. 그 중 비관락, 낙관락이라는 개념이 있다. 비관락(Pessimistic lock) : 트랜잭션이 시작 될 때 공유락과 베타락을 거는 방식으로 Repeatable Read 또는 Serializable 정도의 격리성 수준을 제공한다
낙관락 : 자원에 락을 걸지 않고 동시성 문제가 발생할면 그때 처리하는 방식
성능 측면 비교
|
Beta Was this translation helpful? Give feedback.
-
낙관락(Optimistic Lock)과 비관락(Pessimistic Lock)은 데이터베이스 트랜잭션에서 동시성 제어를 위한 두 가지 주요 기법입니다.
낙관락 (Optimistic Lock)
4번 첨언
# transaction 1
select * from reservation
where id = 1; # 이 때 version = 1 상태
# transaction 2
select * from reservation
where id = 1; # 이 때 version = 1 상태
# transaction 1
update set status = 'ACCEPTED', version = version + 1
from reservation
where id = 1 and version = 1; # version = 2로 업데이트
# transaction 2
update set status = 'CANCELED', version = version + 1
from reservation
where id = 1 and version = 1; # version = 1이 없기 때문에 단순히 0개 row 업데이트 (예외 x)
JPA에서 사용하기@Entity
public class Reservation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// ...
@Version
private Long version;
} public interface ReservationRepository extends JpaRepository<Reservation, Long> {
@Lock(LockModeType.OPTIMISTIC)
@Query("select r from Reservation r where r.id = :id")
Optional<Reservation> findByIdWithOptimisticLock(Long id);
} 비관락 (Pessimistic Lock)
S-LockRead Lock이라고도 하며 다른 트랜잭션에서 write 작업을 수행하지 못하도록 한다.
X-LockWrite Lock이라고도 하며 다른 트랜잭션에서 write 작업 및 S-Lock을 획득하지 못하도록 한다.
JPA에서 사용하기public interface ReservationRepository extends JpaRepository<Reservation, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select r from Reservation r where r.id = :id")
Optional<Reservation> findByIdWithPessimisticLock(Long id);
}
결론
추가 키워드
|
Beta Was this translation helpful? Give feedback.
-
.
Beta Was this translation helpful? Give feedback.
All reactions