MySQL的异步调用模块
发布时间:2020-12-15 21:10:45 所属栏目:大数据 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 package MySQLDBI;use EV;use DBI;use base 'Exporter';use strict;our @EXPORT = qw(create_dbh_pool get_dbh put_dbh dbh_exec);my $dbh_pool = [];
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 package MySQLDBI; use EV; use DBI; use base 'Exporter'; use strict; our @EXPORT = qw(create_dbh_pool get_dbh put_dbh dbh_exec); my $dbh_pool = []; my ($db_name,$db_host,$db_user,$db_pass) ; #create dbh pool sub create_dbh_pool { ($db_name,$db_pass,$size) = @_; for ( 1 .. $size ) { my $dbh = DBI->connect( "dbi:mysql:database=$db_name;host=$db_host",{mysql_enable_utf8 => 1,'RaiseError'=>1},); $dbh->do('set SESSION wait_timeout=72000'); $dbh->do('set SESSION interactive_timeout=72000'); push(@{$dbh_pool},{ handle => $dbh,} ); } } #get dbh handle from pool sub get_dbh { return pop @{$dbh_pool} if scalar(@{$dbh_pool}); my $dbh = DBI->connect( "dbi:mysql:database=$db_name;host=$db_host",); $dbh->do('set SESSION wait_timeout=72000'); $dbh->do('set SESSION interactive_timeout=72000'); return { handle => $dbh,}; } #put dbh handle back to pool sub put_dbh { push(@{$dbh_pool},shift); } #exec sql statement. when mysql has result back,call callback func. sub dbh_exec { my ($st,$args,$cb) = @_; my $dbh = get_dbh(); return $cb->(undef,undef) unless $dbh ; my $sth = undef; $sth = $dbh->{handle}->prepare($st,{async =>1}); if ( $args ) { eval {$sth->execute(@{$args})}; } else { eval { $sth->execute() } } my $w; if ( [email?protected] =~ /gone/i ) { undef $dbh; $dbh = DBI->connect( "dbi:mysql:database=$db_name;host=$db_host","$db_user","$db_pass",'RaiseError'=>1} ) or die "can not connect to db!n"; $dbh->do('set SESSION wait_timeout=72000'); $dbh->do('set SESSION interactive_timeout=72000'); $sth = $dbh->prepare($st,{async=>1}); $w = EV::io $dbh->mysql_fd,EV::READ,sub{ $cb->($dbh,$sth); delete $dbh->{w}; put_dbh({ handle => $dbh}); }; if ( $args ) { eval {$sth->execute(@{$args})}; } else { eval { $sth->execute() } } } $w = EV::io $dbh->{handle}->mysql_fd,sub{ my $w=shift; $cb->($dbh,$sth); delete $dbh->{w}; put_dbh($dbh); }; $dbh->{w} = $w; } 1; __END__ =pod =head1 NAME MySQLDBI - a MySQL async caller DBI =head1 SYNOPSIS use MySQLDBI; create_dbh(...); $dbh = get_dbh(); $dbh->dbh_exec("SQL statement",$args_array_ref,sub { my ($dbh,$sth) = @_; #... }); 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |