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
}