Too many DB connections with mod_perl2 moose application

I have a mod_perl2 based web application that requires a connection to the mysql database. I applied the specification of the SQL connection as an elk.

Simplified, the role is 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;

Then I use this role in all moose classes that require a database connection using

 with qw(Project::Role::SQLConnection);

statement.

While this works well when multiple objects are created, I will soon encounter problems when many objects are created. For example, in the httpd log I get an error:

DBI connect ('alcatelRSA; host = 10.125.1.21; port = 3306', 'tools', ...) failed: Too many connections on C: /Perl/site/lib/DBIx/Connector.pm line 30

DBIx:: Connectors "disconnect", , / .

?

+3
1

dbh , DBIx::Connector ? , . DBIx:: Connector dbh handles .

, ( , , DB ):

has dbixc => (
    is => 'ro', isa => 'DBIx::Connector',
    lazy_build => 1,
    # DO NOT save a copy of the dbh. Use this accessor every time, as
    # sometimes it will change unexpectedly!
    handles => [ qw(dbh) ],
);

sub _build_dbixc
{
    my $this = shift;
    DBIx::Connector->new(
        $this->dsn,
        $this->username,
        $this->password,
        $this->connect_options,
    );
}

sub call_dbh
{
    my $this = shift;
    my $method = shift;
    my @args = @_;

    # the normal behaviour -- pings on every dbh access
    #return $this->dbh->$method(@args);

    # the smart behaviour -- presume the DB connection still works
    $this->dbixc->run(fixup => sub { $_->$method(@args) });
}

, mod_perl . , , , , , (.. db) . - MooseX::Singleton, .

+6

Source: https://habr.com/ru/post/1750079/


All Articles