Learn the "why" behind slow queries and how to fix them in our 2-Part Webinar.
Register now >
Docs Menu
Docs Home
/ /

연결 풀 사용

이 가이드 에서는 C++ 운전자 사용하여 연결 풀 만들고 구성하는 방법을 학습 수 있습니다. 연결 풀 애플리케이션 여러 개의 동시 MongoDB 작업을 관리 데 사용할 수 있는 클라이언트 객체의 캐시 입니다.

mongocxx::pool을 인스턴스화한 후 풀은 최대 풀 크기에 도달할 때까지 필요에 따라 클라이언트 객체를 생성합니다. MongoDB 작업을 실행하는 각 스레드는 풀에서 클라이언트 체크아웃하고 이를 사용하여 작업을 수행하고 클라이언트 를 풀로 반환합니다. 풀은 이러한 클라이언트의 수명 주기를 자동으로 관리합니다.

중요

대부분의 MongoDB 드라이버와 달리 C++ 운전자 MongoDB 연결 모니터링 및 풀링 (CMAP) 사양을 구현 하지 않습니다. 여기서 연결 풀링 데이터베이스 연결 대신 드라이버의 클라이언트 객체 캐시 말합니다.

연결 풀은 독립형 클라이언트에 비해 상당한 성능 이점을 제공합니다. mongocxx::pool 은(는) 별도의 배경 모니터링 스레드를 사용하여 클러스터 를 지속적으로 모니터 . 결과적으로 애플리케이션 스레드는 토폴로지 모니터링 완료될 때까지 기다리지 않고 작업을 수행할 수 있습니다. 반면 독립형 mongocxx::client 는 클러스터 상태를 확인하기 위해 주기적으로 중지하여 확인하는 동안 모든 작업을 차단합니다.

애플리케이션 에서 스레드를 하나만 사용하는 경우에도 연결 풀 사용할 수 있습니다. 풀의 배경 모니터링 독립형 클라이언트의 주기적인 검사보다 더 나은 성능을 제공합니다.

다음 표에는 mongocxx::poolmongocxx::client의 주요 차이점이 요약되어 있습니다.

기능
mongocxx::pool
mongocxx::client

멀티스레드 애플리케이션에 권장

예.

No.

백그라운드 모니터링

네. 풀은 각 서버 에 대해 별도의 스레드를 사용합니다.

아니요. 클라이언트는 주기적으로 차단 검사를 수행합니다.

모니터링 간격

서버 당 10 초마다

60 초마다.

스레드 안전성

스레드로부터 안전하지만 획득한 클라이언트는 스레드로부터 안전하지 않습니다.

스레드로부터 안전하지 않습니다.

포크 안전성

포크 후 풀을 생성해야 합니다.

포크 후 클라이언트 생성해야 합니다.

스레딩 및 포크

여러 스레드에서 클라이언트 및 클라이언트 객체를 사용하는 방법과 프로세스를 포크하는 경우에 대해 자세히 학습 스레드 및 포크 안전 가이드 참조하세요.

연결 풀 만들려면 연결 URI를 생성자에 전달하여 mongocxx::pool 객체 인스턴스화합니다. MongoDB 작업을 실행하는 각 스레드는 acquire() 멤버 함수를 호출하여 풀에서 클라이언트 획득해야 합니다. 클라이언트 범위를 벗어나면 자동으로 풀로 돌아갑니다.

이 샘플 파일 다음 조치를 수행합니다.

  • 연결 풀 생성합니다.

  • 각각 풀에서 자체 클라이언트 획득하는 3개의 스레드를 생성합니다.

  • 각 스레드에서 삽입 작업을 수행합니다.

1#include <iostream>
2#include <thread>
3#include <vector>
4
5#include <bsoncxx/builder/basic/document.hpp>
6#include <bsoncxx/builder/basic/kvp.hpp>
7#include <mongocxx/instance.hpp>
8#include <mongocxx/pool.hpp>
9#include <mongocxx/uri.hpp>
10
11using bsoncxx::builder::basic::kvp;
12using bsoncxx::builder::basic::make_document;
13
14int main() {
15 mongocxx::instance instance{};
16
17 mongocxx::uri uri{"mongodb://localhost:27017"};
18 mongocxx::pool pool{uri};
19
20 std::vector<std::thread> threads;
21
22 // Creates multiple threads that each acquire a client from the pool
23 for (int i = 0; i < 3; ++i) {
24 threads.emplace_back([&pool, i]() {
25 auto client = pool.acquire();
26 auto collection = (*client)["db"]["coll"];
27
28 // Inserts a sample document
29 collection.insert_one(make_document(kvp("thread_id", i)));
30
31 std::cout << "Thread " << i << " inserted a document" << std::endl;
32 });
33 }
34
35 // Waits for all threads to complete
36 for (auto& thread : threads) {
37 thread.join();
38 }
39
40 std::cout << "All threads completed" << std::endl;
41
42 return 0;
43}

연결 URI에 옵션을 포함하여 연결 풀 동작을 구성할 수 있습니다. 다음 표에서는 설정하다 수 있는 연결 풀 옵션에 대해 설명합니다.

URI 옵션
설명

maxPoolSize

Specifies the maximum number of clients the pool can create. When this limit is reached, the acquire() member function blocks until another thread returns a client to the pool.
Defaults to 100.
Type: int

minPoolSize

Specifies the minimum number of clients the pool maintains. The pool creates this number of clients when initialized and maintains at least this number of clients continuously.
Defaults to 0.
Type: int

waitQueueTimeoutMS

Specifies the maximum time in milliseconds that the acquire() function waits for a client to become available when the pool has reached the maxPoolSize value. If this timeout expires, the acquire() function generates an error.
Defaults to no timeout.
Type: int

다음 예시 maxPoolSize 옵션을 지정하여 최대 크기가 5 클라이언트인 연결 풀 생성합니다.

mongocxx::uri uri{"mongodb://localhost:27017/?maxPoolSize=5"};
mongocxx::pool pool{uri};

이 가이드 에서 설명하는 유형 및 함수에 대해 자세히 학습 다음 API 문서를 참조하세요.

돌아가기

Stable API

이 페이지의 내용