in reply to Re: for perl, how to manage tht mongodb connection pool?
in thread for perl, how to manage tht mongodb connection pool?

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.
  • Comment on Re^2: for perl, how to manage tht mongodb connection pool?

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

    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 }