liuweichuan has asked for the wisdom of the Perl Monks concerning the following question:

for perl, how to manage tht mongodb connection pool? I know it's a connection pool when building an instance, and you can "get" one or more connection. my code is as below,

use MongoDB; our $conn; if(!defined($conn)){ $log->info("Creating new DB connection"); $conn = MongoDB::MongoClient->new; } else{ $log->info("DB connection already exists"); } ...do something...

but, i don't know how to coding the "our $conn" as gloabl arivable. I think the $conn is a long runing connetion, right?

Replies are listed 'Best First'.
Re: for perl, how to manage tht mongodb connection pool?
by Corion (Patriarch) on Sep 13, 2016 at 08:05 UTC

    our $conn already declares the name for a global variable.

    What is the specific problem you encounter?

      my problem is that i don't know clearly how to build and manage mongodb connection pool, i want to make a pool by the code. but i don't think it's right. my thinking is that step 1, a global varaiable "new instance", and step 2, some clients share this instance or get connection from the pool.

        The easy way to manually a connection (pool) is to use a function to get a connection:

        use MongoDB; our $mongodb; sub mongodb() { if(!defined($mongodb)){ $log->info("Creating new DB connection"); $mongodb = MongoDB::MongoClient->new; } else{ $log->info("DB connection already exists"); } return $mongodb };

        And then everywhere in your code, you don't use $mongodb but mongodb() instead.

        If you want to extend that to a connection pool, you can either have your code manually return finished connections to the pool or write something that makes this automatic.

        my $max_mongodb_connections = 4; our @mongodb_pool; our %used_connections; sub mongodb() { my $mongodb; if(@mongodb_pool){ $log->info("Using existing DB connection from pool"); $mongodb = shift @mongodb_pool; } elsif(@mongodb_pool and keys %used_connections < $max_mongodb_conn +ections){ $log->info("Creating new DB connection"); $mongodb = MongoDB::MongoClient->new; } else{ $log->info("Need to wait until a mongodb connection becomes availa +ble"); } $used_connections{ $mongodb } = 1 if $mongodb; return $mongodb }; sub return_connection { my( $mongodb )= @_; delete $used_connections{ $mongodb }; unshift @mongodb_pool, $mongodb; # keep the hot connections hot }