문서 메뉴
문서 홈
/ / /
Go
/

트랜잭션

이 페이지의 내용

  • 개요
  • 방법
  • 예제
  • 추가 정보
  • API 문서

이 가이드에서는 MongoDB Go 드라이버를 사용하여 트랜잭션을 수행하는 방법을 배울 수 있습니다. 트랜잭션을 사용하면 트랜잭션이 커밋될 때까지 데이터를 변경하지 않는 일련의 작업을 실행할 수 있습니다. 트랜잭션에서 오류가 반환되는 경우 드라이버는 트랜잭션을 취소하고 데이터 변경 사항이 표시되기 전에 모든 데이터 변경 사항을 삭제합니다.

MongoDB에서 트랜잭션은 논리적 세션 내에서 실행됩니다. 세션은 순차적으로 실행하려는 관련 읽기 또는 쓰기 작업의 그룹입니다. 세션을 사용하면 작업 그룹에 대한 인과적 일관성을 유지하거나 ACID transaction 에서 작업을 실행할 수 있습니다. MongoDB는 작업에 예상치 못한 오류가 발생하더라도 트랜잭션 작업과 관련된 데이터의 일관성을 보장합니다.

Go 드라이버를 사용하는 경우 Client 인스턴스에서 Session 유형으로 새 세션을 만들 수 있습니다. 매번 새 클라이언트를 인스턴스화하는 대신 여러 세션 및 트랜잭션에 클라이언트를 재사용할 것을 권장합니다.

경고

Session 는 이를 생성한 Client (또는 연결된 Database 또는 Collection)에만 사용해야 합니다. 다른 Client 와(과) 함께 Session 을(를) 사용하면 작업 오류가 발생합니다.

경고

Session의 구현은 여러 goroutine에서 동시에 사용하기에 안전하지 않습니다.

StartSession() 메서드를 사용하여 세션을 시작한 후 Session 인터페이스에서 제공하는 메서드 세트를 사용하여 세션 상태를 수정할 수 있습니다. 다음 표에서는 이러한 메서드에 대해 설명합니다:

메서드
설명
StartTransaction()
Starts a new transaction, configured with the given options, on this session. Returns an error if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions
Return Type: error
AbortTransaction()
Ends the active transaction for this session. Returns an error if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

Parameter: Context
Return Type: error
CommitTransaction()
Commits the active transaction for this session. Returns an error if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.

참고

트랜잭션 재시도

CommitTransaction() 메서드는 멱등 함수입니다. 즉, 첫 번째 커밋 성공 후 데이터를 변경하지 않고도 트랜잭션을 여러 번 커밋할 수 있습니다.

트랜잭션은 성공할 수 있지만 UnknownTransactionCommitResult 레이블과 함께 오류를 반환합니다. 이 오류가 발생한 후 CommitTransaction() 메서드를 다시 실행하면 반복 시도에 의해 데이터가 변경되지 않습니다.


Parameter: Context
Return Type: error
WithTransaction()
Starts a transaction on this session and runs the fn callback.

Parameters: Context, fn func(ctx SessionContext), TransactionOptions
Return Type: interface{}, error
EndSession()
Ends any existing transactions and closes the session.

Parameter: Context
Return Type: none

Session 인터페이스에는 세션 속성을 검색하고 변경 가능한 세션 속성을 수정하는 메서드도 있습니다. 자세한 내용은 API 문서를 참조하세요.

다음 예시에서는 다음 단계를 통해 세션을 생성하고, 트랜잭션을 생성하고, 다중 문서 삽입 작업을 커밋하는 방법을 보여줍니다.

  1. StartSession() 메서드를 사용하여 클라이언트에서 세션을 만듭니다.

  2. WithTransaction() 메서드를 사용하여 트랜잭션을 시작합니다.

  3. 여러 문서를 삽입합니다. WithTransaction() 메서드는 삽입을 실행하고 트랜잭션을 커밋합니다. 작업 중 오류가 발생하면 WithTransaction() 이 트랜잭션 중단을 처리합니다.

  4. EndSession() 메서드를 사용하여 트랜잭션 및 세션을 닫습니다.

wc := writeconcern.New(writeconcern.WMajority())
txnOptions := options.Transaction().SetWriteConcern(wc)
session, err := client.StartSession()
if err != nil {
panic(err)
}
defer session.EndSession(context.TODO())
result, err := session.WithTransaction(context.TODO(), func(ctx mongo.SessionContext) (interface{}, error) {
result, err := coll.InsertMany(ctx, []interface{}{
bson.D{{"title", "The Bluest Eye"}, {"author", "Toni Morrison"}},
bson.D{{"title", "Sula"}, {"author", "Toni Morrison"}},
bson.D{{"title", "Song of Solomon"}, {"author", "Toni Morrison"}},
})
return result, err
}, txnOptions)

트랜잭션에 더 많은 제어가 필요한 경우 전체 코드 예시에서 트랜잭션을 수동으로 생성, 커밋 및 종료하는 방법을 보여주는 예시를 찾을 수 있습니다.

삽입 작업에 대한 자세한 내용은 문서 삽입 기본 사항 페이지를 참조하세요.

쓰기 고려에 대한 자세한 내용 은 CRUD 작업의 실행 수정 기본 사항 페이지를 참조하세요.

Go 드라이버로 세션 및 트랜잭션을 사용하는 추가 예시는 다중 문서 ACID 트랜잭션에 대한 개발자 블로그 포스트를 참조하세요.

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

돌아가기

색인