Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^3: for perl, how to manage tht mongodb connection pool?

by Corion (Patriarch)
on Sep 13, 2016 at 09:53 UTC ( [id://1171649]=note: print w/replies, xml ) Need Help??


in reply to Re^2: for perl, how to manage tht mongodb connection pool?
in thread for perl, how to manage tht mongodb connection 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 }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1171649]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-19 20:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found