I have a mod_perl2 based web app that requires a connection to a mysql database. I have implemented the SQL connection specifics in a moose role.
Simplified, the role looks as follows:
package Project::Role::SQLConnection;
use Moose::Role;
use DBIx::Connector;
has 'connection' => (is => 'rw', lazy_build => 1);
has 'dbh' => (is => 'rw', lazy_build => 1);
has 'db' => ( is => 'rw', default => 'alcatelRSA');
has 'port' => ( is => 'rw', default => 3306);
has 'host' => ( is => 'rw', default => '10.125.1.21');
has 'user' => ( is => 'rw', default => 'tools');
has 'pwd' => ( is => 'rw', default => 'alcatel');
#make sure connection is still alive...
before dbh => sub {
my $self = shift;
$self->connection->run(fixup => sub { $_->do('show tables') });
};
sub _build_dbh {
my $self = shift;
return $self->connection->dbh;
}
sub _build_connection {
my $self = shift;
my $dsn = 'DBI:mysql:'.$self->db.';host='.$self->host.';port='.$self->port;
my $conn = DBIx::Connector->new($dsn, $self->user, $self->pwd);
return $conn;
}
no Moose::Role;
1;
I then use this role in all moose classes that require a connection to the DB with a
with qw(Project::Role::SQLConnection);
statement.
While this works well when a few objects are created, i soon run into troubles when to many objects are created. In the httpd log for instance, i get the error:
DBI connect('alcatelRSA;host=10.125.1.21;port=3306','tools',...) failed: Too many connections at C:/Perl/site/lib/DBIx/Connector.pm line 30
I thought about using DBIx::Connectors "disconnect" call to close the connection to the database each time, but the performance impact seem to severe to open / close connections as required.
Do you have any alternative suggestions on this problem?