mysql - Perl 连接池

标签 mysql perl apache mod-perl

现在我们有一个大型 perl 应用程序,它使用原始 DBI 连接到 MySQL 并执行 SQL 语句。它每次都会创建一个连接并终止。开始接近mysql的连接限制(一次200)

看起来像 DBIx::Connection支持应用层连接池。

有人对 DBIx::Connection 有任何经验吗?连接池还有其他注意事项吗?

我还看到了 mod_dbd,它是一个 Apache 模块,看起来像是处理连接池。 http://httpd.apache.org/docs/2.1/mod/mod_dbd.html

最佳答案

我对 DBIx::Connection 没有任何经验,但我使用 DBIx::Connector (本质上是 DBIx::Class 在内部使用的东西,但是是内联的)而且它很棒......

我将这些连接与 Moose 对象包装器汇集在一起​​,如果连接参数相同(这对任何底层 DB 对象都一样),该包装器会返回现有对象实例:

package MyApp::Factory::DatabaseConnection;
use strict;
use warnings;

use Moose;

# table of database name -> connection objects
has connection_pool => (
    is => 'ro', isa => 'HashRef[DBIx::Connector]',
    traits  => ['Hash'],
    handles => {
        has_pooled_connection => 'exists',
        get_pooled_connection => 'get',
        save_pooled_connection => 'set',
    },
    default => sub { {} },
);

sub get_connection
{
    my ($self, %options) = @_;

    # some application-specific parsing of %options here...

    my $obj;
    if ($options{reuse})
    {
        # extract the last-allocated connection for this database and pass it
        # back, if there is one.
        $obj = $self->get_pooled_connection($options{database});
    }

    if (not $obj or not $obj->connected)
    {
        # look up connection info based on requested database name
        my ($dsn, $username, $password) = $self->get_connection_info($options{database});
        $obj = DBIx::Connector->new($dsn, $username, $password);

        return unless $obj;

        # Save this connection for later reuse, possibly replacing an earlier
        # saved connection (this latest one has the highest chance of being in
        # the same pid as a subsequent request).
        $self->save_pooled_connection($options{database}, $obj) unless $options{nosave};
    }

    return $obj;
}

关于mysql - Perl 连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3267591/

相关文章:

php - 使用事件名称而不是 ID 删除记录

apache - 301重定向重写规则用连字符替换下划线并删除子目录

perl - 如何检查我的 Perl 安装是 32 位还是 64 位?

linux - nginx/apache重定向vps上docker容器上的输出端口

apache - 如何使基本身份验证排除重写的 URL

mysql - 确定哪些列与搜索条件匹配

mysql - 用于标准化数据的复杂分组功能

mysql - MySQL可以将外部数据库复制到云吗

perl - Perl 脚本可以修改自身吗?

bash - Perl $ENV 不访问环境变量