How to manage MongoDB connections on Perl/Mason website

639 Views Asked by At

I'm trying to write a website in Perl with Mason. I setup a server with the following: - Apache with mod_perl with Mason - CGI::Session for managing session - MongoDB for database.

My concern is, each time I connect to my MongoDB database, the connection stays alive until I restart httpd service. Thus, if the maximum connection is reached, I can't open anymore connections.

Does anyone have a way to:

  • either close the connection (which might not be a good idea) ?
  • either have a global pool of db connections knowing the architecture ?
2

There are 2 best solutions below

0
On

The MongoDB driver keeps the connection alive as long as your MongoClient instance exists. In an environment like mod_perl, the Perl interpreter is a persistent process and global variables will hang around until they are destroyed.

If you don't want the connections to be persistent, create a MongoClient object with a scope that will end when the HTTP request cycle is complete. The connections will be closed when the objects are garbage-collected.

If you update your question with more details about how you're creating your client objects I can provide a more detailed answer.

0
On

I've been battling with this recently. I have come up with a very simple solution that works for me. It may not be the best, but seems to do the job just perfectly.

We are using Mojolicious as an API framework running under apache2/mod_perl, and we were finding that new connections were being made quicker than perl MongoDB driver was clearing them up as our webpage was calling the API to fetch new data.

So, I put in a simple...

use strict;
use warnings;
use MongoDB;

our $conn;

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

sub fetchData {
    # Do Mongo get/find stuff in here

    my $dbh = $mongoConn->get_database($db);
    my $collection = $dbh->get_collection($col);
    my $cursor = $collection->find($q)->fields($fieldsObj);
    my @result = $cursor->all;
    return @result;
}

Obviously I've omitted error catching, and the else isn't necessary, but hopefully this will help someone like me looking for a solution to this.