Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Menu Docs
Página inicial do Docs
/ / /
Driver C
/ /

Pool de conexões

O driver do MongoDB C tem dois modos de conexão: thread único e pool. O modo de thread único é otimizado para incorporar o driver em linguagens como PHP. Programas com várias threads devem usar o modo pool: esse modo minimiza a contagem total de conexões e, no modo pool, as threads em segundo plano monitoram a topologia do servidor MongoDB para que o programa não precise bloquear sua verificação.

In single mode, your program creates a mongoc_client_t directly:

mongoc_client_t *client = mongoc_client_new (
"mongodb://hostA,hostB/?replicaSet=my_rs");

O cliente se conecta sob demanda quando seu programa o usa pela primeira vez para uma operação do MongoDB . Usando um soquete sem bloqueio por servidor, ele inicia uma verificação em cada servidor simultaneamente e usa a função assíncrona poll ou select para receber eventos dos soquetes, até que todos tenham respondido ou atinja o tempo limite. Em outras palavras, no modo de thread único, o Driver C é ativado para iniciar todas as verificações simultaneamente e, em seguida, é ativado quando todas as verificações tiverem sido concluídas ou expiradas. Depois que a verificação for concluída, o cliente executará a operação do seu programa e retornará.

In single mode, the client re-scans the server topology roughly once per minute. If more than a minute has elapsed since the previous scan, the next operation on the client will block while the client completes its scan. This interval is configurable with heartbeatFrequencyMS in the connection string. (See mongoc_uri_t.)

Um único cliente abre uma conexão por servidor em sua topologia: essas conexões são usadas tanto para verificar a topologia quanto para executar operações normais.

To activate pooled mode, create a mongoc_client_pool_t:

mongoc_uri_t *uri = mongoc_uri_new (
"mongodb://hostA,hostB/?replicaSet=my_rs");
mongoc_client_pool_t *pool = mongoc_client_pool_new (uri);

When your program first calls mongoc_client_pool_pop, the pool launches monitoring threads in the background. Monitoring threads independently connect to all servers in the connection string. As monitoring threads receive hello responses from the servers, they update the shared view of the server topology. Additional monitoring threads and connections are created as new servers are discovered. Monitoring threads are terminated when servers are removed from the shared view of the server topology.

Cada thread que executa operações MongoDB deve fazer check-out de um cliente do pool:

mongoc_client_t *client = mongoc_client_pool_pop (pool);
/* use the client for operations ... */
mongoc_client_pool_push (pool, client);

The mongoc_client_t object is not thread-safe, only the mongoc_client_pool_t is.

Quando o driver está no modo pool, as operações do seu programa são desbloqueadas assim que o monitoramento descobre um servidor utilizável. Por exemplo, se um thread em seu programa estiver esperando para executar uma "inserção" no primário, ele será desbloqueado assim que o primário for descoberto, em vez de esperar que todos os secundários também sejam verificados.

The pool opens one connection per server for monitoring, and each client opens its own connection to each server it uses for application operations. Background monitoring threads re-scan servers independently roughly every 10 seconds. This interval is configurable with heartbeatFrequencyMS in the connection string. (See mongoc_uri_t.)

The connection string can also specify waitQueueTimeoutMS to limit the time that mongoc_client_pool_pop will wait for a client from the pool. (See mongoc_uri_t.) If waitQueueTimeoutMS is specified, then it is necessary to confirm that a client was actually returned:

mongoc_uri_t *uri = mongoc_uri_new (
"mongodb://hostA,hostB/?replicaSet=my_rs&waitQueueTimeoutMS=1000");
mongoc_client_pool_t *pool = mongoc_client_pool_new (uri);
mongoc_client_t *client = mongoc_client_pool_pop (pool);
if (client) {
/* use the client for operations ... */
mongoc_client_pool_push (pool, client);
} else {
/* take appropriate action for a timeout */
}

See connection pool options to configure pool size and behavior, and see mongoc_client_pool_t for an extended example of a multi-threaded program that uses the driver in pooled mode.

Voltar

Conexões avançadas

Nesta página