与 Catalyst 的持久数据库连接

Persistent database connections with Catalyst

我的组织有一个自定义包用于连接到我们的数据库服务器,它负责随机尝试各种镜像(根据配置文件)并且只尝试主数据库服务器进行非只读连接,或者如果 none 的镜子可以到达。我想接受并使用它在 Catalyst 应用程序中建立持久连接。

我尝试的是基于 Catalyst::Model::DBI 创建一个模型包,但它重新定义了模块的 connect() 方法以使用我们包的连接方法。然后我重新定义了 "selectall_arrayref"、"do" 使用 stay_connected() 的方法...它工作正常但是它为每个查询创建了一个新连接 - 即使在同一个 http 请求期间Catalyst::Model::DBI 的文档似乎暗示连接应该是持久的。

所以我的问题是,应该发生什么?我是否需要做一些不同的事情来获得持久句柄? Model::DBI 通常会提供吗?如果是这样,我如何将我们的这个东西移植到其中,或者有更好更简单的方法吗?我不想重新编写整个包来使用 DBIx::Class,我只想插入我们的例程,为我提供适合我们系统的数据库句柄。

package SpamControl::Model::Database;
use strict;
use Freecycle::Database;

use base 'Catalyst::Model::DBI';

# redefine the connect method, this is just copied from Model::DBI but  using the Freecycle package for the actual connection.
sub connect {
    my $self = shift;
    my $dbh;
    # TODO: I wish this could be a persistent connection.
    eval {
            $dbh = Freecycle::Database::connect({ username => 'member', read_only => 1 });
    };
    if ($@) { $self->{log}->debug( qq{Couldn't connect to the database "$@"} ) if $self->{debug} }
    else { $self->{log}->debug ( 'Connected to the database')  if $self->{debug}; }
    $self->_pid( $$ );
    $self->_tid( threads->tid ) if $INC{'threads.pm'};
    return $dbh;
}

# for read/write connections
sub dbh_admin {
    my ($self,$c) = @_;
    my $dbh = Freecycle::Database::connect({ username => 'admin', read_only => 0 });
    return $dbh;
}

sub do {
    my $self = shift;
    return $self->dbh_admin->do(@_);
}

sub selectall_hashref {
    my $self = shift;
    return $self->stay_connected->selectall_hashref(@_);
}

...etc etc.

Catalyst::Model::DBI provides persistent connections and automatic re-connections (through DBIx::Connector 如今。

如果你有一个模块已经这样做了(Freecycle::Database?)你根本不应该使用 Catalyst::Model::DBI,而是将你的模块用作 Catalyst 模型,Catalyst::Model::Adaptor 可以帮上大忙。