Skip to content

Instantly share code, notes, and snippets.

@ggl
Created November 10, 2022 06:50
Show Gist options
  • Save ggl/a3b62ef4529fb304cee71d498f9d7eb5 to your computer and use it in GitHub Desktop.
Save ggl/a3b62ef4529fb304cee71d498f9d7eb5 to your computer and use it in GitHub Desktop.
POE::Component::EasyDBI example
#!/usr/bin/env perl
use strict;
use warnings;
use lib 'lib';
use POE qw(Component::EasyDBI);
use Data::Dumper;
POE::Session->create(
inline_states => {
_start => \&start,
stop => sub {},
db_connect => \&db_connect,
db_query => \&db_query,
db_error => \&db_error,
db_result => \&db_result,
},
heap => {
cursor => 0,
queries => [
'SELECT UNIX_TIMESTAMP() AS ts',
'SELECT RAND() AS rnd',
'SELECT NOW() as now'
]
}
);
POE::Kernel->run;
sub db_connect {
print join(' ', 'Connect', time(), "\n");
$_[KERNEL]->post(db_test => 'db_query');
}
sub db_query {
if ($_[HEAP]->{cursor} > $#{$_[HEAP]->{queries}}) {
$_[HEAP]->{cursor} = 0;
}
my $query = $_[HEAP]->{queries}->[$_[HEAP]->{cursor}++];
if (!$query) {
return;
#$_[KERNEL]->post('easydbi', shutdown => 'NOW');
}
#print Dumper $_[KERNEL]->call('easydbi', 'print_queue');
$_[KERNEL]->post('easydbi',
arrayhash => {
sql => $query,
event => 'db_result',
}
);
$_[KERNEL]->delay('db_query', 5);
}
sub db_error {
my $err = ref $_[ARG0] eq 'HASH' && $_[ARG0]->{error} ? $_[ARG0]->{error} : q{};
warn join (' ', 'Error', time(), $err, "\n");
$_[HEAP]->{db_error}++;
}
sub db_result {
my $res = ref $_[ARG0] eq 'HASH' && ref $_[ARG0]->{result} eq 'ARRAY' && ref $_[ARG0]->{result}[0] eq 'HASH' ? $_[ARG0]->{result}[0] : {};
print join(' ', 'Result', time(), $_[ARG0]->{id}, %$res, "\n");
}
sub start {
$_[KERNEL]->alias_set('db_test');
my $dsn = "dbi:mysql:database=test;host=localhost;port=3306";
my ($user, $pass) = ('auser', 'apass');
$_[HEAP]->{easydbi} = POE::Component::EasyDBI->new(
alias => 'easydbi',
dsn => $dsn,
username => $user,
password => $pass,
no_connect_failures => 1,
max_retries => -1,
ping_timeout => 60,
alt_fork => 1,
stopwatch => 1,
connect_error => ['db_test', 'db_error'],
connected => ['db_test', 'db_connect']
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment