Apache::Session::Wrapperの保存先をPostgreSQLにする

mod_perlハンドラでセッションを使 ではApacheが動いているマシンに1セッション1ファイルで情報を保存しましたが、保存先をPostgreSQLのデータベースに変更してみます。


最初にセッション情報を保存するデータベースにテーブルを作ります。アプリケーションのデータを持っているデータベースの中に作っても良いし、それとは別にセッション用のデータベースを作ってもかまいせん。必要なテーブルについては perldoc Apache::Session::Store::Postgres に書いてあります。

CREATE TABLE sessions (
    id char(32) not null primary key,
    a_session text
);

セッションに保存するハンドラ

Apache::Session::Wrapperでは保存に「Postgres」クラスを使うことを指定します。

package My::PgDbhSaveSession;
use strict;

use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Const -compile => 'OK';

use Apache::Session::Wrapper;
use DBI;

sub handler : method {
    my ($class, $r) = @_;
    $r->content_type('text/html');

    my $dbh = DBI->connect("dbi:Pg:dbname=app_db", "hiramatsu", "", {AutoCommit => 0});
    my $wrapper = Apache::Session::Wrapper->new(
                    class  => 'Postgres',
                    handle => $dbh,
                    commit => 1,
                    use_cookie => 1,
                 );
    $wrapper->session->{test_param} = 'test string';

    print q|<a href="/db_session_show">show_session</a>|;
    return Apache2::Const::OK;
}

1;

セッションを読み出すハンドラ

package My::PgDbhShowSession;
use strict;

use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Const -compile => 'OK';

use Apache::Session::Wrapper;
use DBI;

sub handler : method {
    my ($class, $r) = @_;
    $r->content_type('text/plain');

    my $dbh = DBI->connect("dbi:Pg:dbname=app_db", "hiramatsu", "", {AutoCommit => 0});
    my $wrapper = Apache::Session::Wrapper->new(
                    class  => 'Postgres',
                    handle => $dbh,
                    commit => 1,
                    use_cookie => 1,
                 );
    print $wrapper->session->{test_param};

    return Apache2::Const::OK;
}

1;