Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Scala드라이버
/

거래 수행

이 가이드 에서는 스칼라 운전자 사용하여 트랜잭션을 수행하는 방법을 학습 수 있습니다. 트랜잭션을 사용하면 전체 트랜잭션 이 커밋된 경우에만 데이터를 변경하는 일련의 작업을 수행할 수 있습니다. 트랜잭션 의 작업이 성공하지 못하면 운전자 트랜잭션 중지하고 데이터 변경 사항이 표시되기 전에 모든 데이터 변경 사항을 삭제합니다. 이 기능 원자성 이라고 합니다.

MongoDB 에서 트랜잭션은 논리적 세션 내에서 실행 . 세션은 순차적으로 실행 하려는 관련 읽기 또는 쓰기 (write) 작업의 그룹입니다. 세션을 사용하면 작업 그룹 에 인과적 일관성 활성화 원자성, 일관성, 격리 및 내구성에 대한 기대치를 충족하는 트랜잭션 인 ACID 호환 트랜잭션 에서 작업을 실행 수 있습니다. MongoDB 작업에 예기치 않은 오류가 발생하더라도 트랜잭션 작업과 관련된 데이터가 일관적인 유지하도록 보장 .

스칼라 운전자 사용하는 경우 클라이언트 에서 startSession() 메서드를 호출하여 ClientSession 를 시작할 수 있습니다. 그런 다음 세션 내에서 트랜잭션을 수행할 수 있습니다.

경고

ClientSession 를 생성한 MongoClient 에서 실행되는 작업에만 를 사용하세요. 다른 MongoClient 와(과) 함께 ClientSession 을(를) 사용하면 작업 오류가 발생합니다.

startSession() 메서드를 호출하여 세션을 시작한 후 ClientSession 클래스의 메서드를 사용하여 세션 상태 수정할 수 있습니다. 다음 표에서는 트랜잭션 관리 데 사용할 수 있는 메서드에 대해 설명합니다.

메서드
설명

startTransaction()

Starts a new transaction on this session. You cannot start a transaction if there's already an active transaction running in the session.

You can set transaction options by passing a TransactionOptions instance as a parameter.

commitTransaction()

Commits the active transaction for this session. This method returns an error if there is no active transaction for the session, the transaction was previously ended, or if there is a write conflict.

abortTransaction()

Ends the active transaction for this session. This method returns an error if there is no active transaction for the session or if the transaction was committed or ended.

트랜잭션 시간 초과

트랜잭션에서 작업을 완료하는 데 걸릴 수 있는 시간 제한을 설정하다 수 있습니다. 자세한 학습 은 서버 실행 시간 제한 가이드 의 트랜잭션 섹션을 참조하세요.

이 예시 sample_mflix 데이터베이스 컬렉션의 데이터를 수정하는 runTransaction() 메서드를 정의합니다. 이 코드는 다음 조치를 수행합니다.

  • MongoCollection 인스턴스를 생성하여 moviesusers 컬렉션에 액세스 .

  • 트랜잭션 에 대한 읽기 및 쓰기 고려 (write concern) 지정합니다.

  • 트랜잭션 시작

  • movies 컬렉션 에 문서 삽입하고 결과를 인쇄합니다.

  • users 컬렉션 의 문서 업데이트하고 결과를 인쇄합니다.

def runTransaction(
database: MongoDatabase,
observable: SingleObservable[ClientSession]
): SingleObservable[ClientSession] = {
observable.map(clientSession => {
val moviesCollection = database.getCollection("movies")
val usersCollection = database.getCollection("users")
val transactionOptions = TransactionOptions
.builder()
.readConcern(ReadConcern.SNAPSHOT)
.writeConcern(WriteConcern.MAJORITY)
.build()
// Starts the transaction with specified options
clientSession.startTransaction(transactionOptions)
// Inserts a document into the "movies" collection
val insertObservable = moviesCollection.insertOne(
clientSession,
Document("name" -> "The Menu", "runtime" -> 107)
)
val insertResult = Await.result(insertObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
println(s"Insert completed: $insertResult")
// Updates a document in the "users" collection
val updateObservable = usersCollection.updateOne(
clientSession,
equal("name", "Amy Phillips"), set("name", "Amy Ryan")
)
val updateResult = Await.result(updateObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
println(s"Update completed: $updateResult")
clientSession
})
}

참고

트랜잭션 내에서 작업은 순서대로 실행 되어야 합니다. 앞의 코드는 작업이 동시에 실행 되지 않도록 각 쓰기 (write) 작업의 결과를 기다립니다.

그런 다음 다음 코드를 실행 하여 트랜잭션 을 수행합니다. 이 코드는 다음 작업을 완료합니다.

  • startSession() 메서드를 사용하여 클라이언트 에서 세션을 생성합니다.

  • 앞의 예시 에서 정의된 runTransaction() 메서드를 호출하여 데이터베이스 와 세션을 매개 변수로 전달합니다.

  • commitTransaction() 메서드를 호출하여 트랜잭션 커밋하고 작업이 완료될 때까지 기다립니다.

val client = MongoClient("<connection string>")
val database = client.getDatabase("sample_mflix")
val session = client.startSession();
val transactionObservable: SingleObservable[ClientSession] =
runTransaction(database, session)
val commitTransactionObservable: SingleObservable[Unit] =
transactionObservable.flatMap(clientSession => clientSession.commitTransaction())
Await.result(commitTransactionObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
Insert completed: AcknowledgedInsertOneResult{insertedId=BsonObjectId{value=...}}
Update completed: AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}

참고

병렬 작업이 지원되지 않음

스칼라 운전자 단일 트랜잭션 내에서 실행 작업 실행을 지원 하지 않습니다.

MongoDB Server v8.0 이상을 사용하는 경우 클라이언트 대량 쓰기 (write) 기능 사용하여 단일 트랜잭션 내의 여러 네임스페이스에서 쓰기 (write) 작업을 수행할 수 있습니다. 이 기능 에 대해 자세히 학습 대량 쓰기 작업 가이드 참조하세요.

이 가이드 에 언급된 개념에 학습 보려면 MongoDB Server 매뉴얼의 다음 페이지를 참조하세요.

  • 트랜잭션

  • 서버 세션

  • 읽기 격리, 일관성 및 최신성

ACID compliance 에 대해 자세히 학습 MongoDB 웹사이트 에서 A Guide to ACID Properties in Database Management Systems(데이터베이스 관리 시스템의 ACID 속성 가이드) 문서를 참조하세요.

삽입 작업에 대해 자세히 알아보려면 문서 삽입 가이드를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.

돌아가기

대량 쓰기 작업

이 페이지의 내용