11

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

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

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

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

4

2 回答 2

9

我对 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;
}
于 2010-07-16T20:50:51.470 回答
5

只要确保:你知道DBI->connect_cached(),对吧?connect()它是在 perl 脚本的整个生命周期内尽可能重用 dbh 的替代品。也许您的问题可以通过添加 7 个字符来解决 :)

而且,MySQL 的连接相对便宜。以或更高的速度运行您的数据库max_connections=1000本身不会导致问题。(如果您的客户要求的工作量超出了您的数据库所能处理的范围,这是一个更严重的问题,一个较低的问题max_connections可能会推迟但当然不能解决。)

于 2010-08-14T17:15:43.587 回答