成都创新互联网站制作重庆分公司

php-fpm连接数据库 php7连接数据库

PHP如何配置TP框架,连接腾讯云云数据库

需要你在阿里云选择一款服务器配置,然后用第三方一键php包的配置,服务器配置出可视化php环境界面,上传程序,安装网站,添加内容。

成都创新互联专注于中卫网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供中卫营销型网站建设,中卫网站制作、中卫网页设计、中卫网站官网定制、小程序定制开发服务,打造中卫网络公司原创品牌,更为您提供中卫网站排名全网营销落地服务。

下载TP5完整版(初学者学习用的)

解压到本地的开发环境中,默认的入口文件是public,访问public会看到TP5成功页面。

开发一个项目的时候,通常分为前台和后台,前台一般放在index模块中,后台一般放在admin模块中。所以你想链接数据库,就去 admin文件夹修改 database.php 连接数据库时候读取的文件,就可以了。

TP框架都这么操作出来的,这是个思路,因为这方面内容较多,这里也写不开那么多内容,在这留言或到咱们的blog找相关内容,可以帮助入门。

怎么安装PHP环境?

LAMP/LNMP 环境搭建

一.检查系统环境

1.确认centos版本

[root@localhost ~]# cat /etc/redhat-release

2.检查是否安装过apache

rpm -qa | grep httpd

或者:

apachectl -v

或者:

httpd -v

3.检查是否安装过Mysql

service mysqld start

如果未被识别则没有安装

如果系统安装过,或者安装失败,清理一下系统

4.清理Mysql痕迹

yum remove mysql

rm -f /etc/my.cnf

5.卸载Apache包

rpm -qa|grep httpd

注意:如果是新的系统或者你从来没有尝试安装过,则以上步骤省略

二.安装Apache、PHP、Mysql

停止防火墙服务

[root@localhost ~]# systemctl stop firewalld.service

禁用防火墙开机启动服务

[root@localhost ~]# systemctl disable firewalld.service

1.安装apache

[root@localhost ~]# yum -y install httpd

2.安装php

[root@localhost ~]# yum -y install php

3.安装php-fpm

[root@localhost ~]# yum -y install php-fpm

4.安装Mysql

[root@localhost ~]# yum -y install mysql

5.安装 mysql-server

[root@localhost ~]# yum install mariadb-server

CentOS 7+ 版本将MySQL数据库软件从默认的程序列表中移除,用mariadb代替了,entos7配置教程上,大多都是安装mariadb,因为centos7默认将mariadb视作mysql。

因为mysql被oracle收购后,原作者担心mysql闭源,所以又写了一个mariadb,这个数据库可以理解为mysql的分支。如果需要安装mariadb,只需通过yum就可。

6.安装 php-mysql

[root@localhost ~]# yum -y install php-mysql

三.安装基本常用扩展包

1.安装Apache扩展包

yum -y install httpd-manual mod_ssl mod_perl mod_auth_mysql

2.安装PHP扩展包

yum -y install php-gd php-xml php-mbstring php-ldap php-pear php-xmlrpc php-devel

3.安装Mysql扩展包

yum -y install mysql-connector-odbc mysql-devel libdbi-dbd-mysql

四.配置Apache、mysql开机启动

重启Apache、mysql服务(注意这里和centos6有区别,Cenots7+不能使用6的方式)

systemctl start httpd.service #启动apache

systemctl stop httpd.service #停止apache

systemctl restart httpd.service #重启apache

systemctl enable httpd.service #设置apache开机启动

重启数据库

#启动MariaDB

[root@localhost ~]# systemctl start mariadb.service

#停止MariaDB

[root@localhost ~]# systemctl stop mariadb.service

#重启MariaDB

[root@localhost ~]# systemctl restart mariadb.service

#设置开机启动

[root@localhost ~]# systemctl enable mariadb.service

五.配置Mysql

初次安装mysql是没有密码的,我们要设置密码,mysql的默认账户为root

方式1:设置 MySQL 数据 root 账户的密码:

[root@localhost ~]# mysql_secure_installation

当出现如下提示时候直接按回车:

Enter current password for root

出现如下再次回车:

Set root password? [Y/n]

出现如下提示输入你需要设置的密码,这里输入了root,输入密码是不显示的,回车后再输入一次确认:

New password:

接下来还会有四个确认,分别是:

Remove anonymous users? [Y/n]

Disallow root login remotely? [Y/n]

Remove test database and access to it? [Y/n]

Reload privilege tables now? [Y/n]

直接回车即可。

方式2:进入mysql mysql -r

修改mysql密码:set password for 'root'@'localhost'=password('root');

mysql授权远程连接(navicat等): grant all on *.* to root identified by 'root';

六.测试环境

我们在浏览器地址栏输入,正常显示,说明我们的lamp 环境搭建成功

七.安装nginx

yum install yum-priorities -y

wget

rpm -ivh nginx-release-centos-7-0.el7.ngx.noarch.rpm

yum install nginx

Nginx 版本号可变更版本

八.配置nginx

1.nginx启动,停止,重启

systemctl start nginx.service #启动nginx

systemctl stop nginx.service #停止

systemctl restart nginx.service #重启

systemctl enable nginx.service #设置开机启动

更改nginx端口号(根据自己需求)

cd /etc/nginx/conf.d/

vim default.conf

把listen 80改成listen 81

3.访问即可看到nginx首页

安装完成访问时候需要启动php-fpm,不重启访问会出现下载文件,重启命令如下

systemctl start php-fpm.service #启动php-fpm

systemctl enable php-fpm.service #设置开机启动

4.更改nginx配置文件识别php

vi /etc/nginx/conf.d/default.conf,把之前的#给去掉就可以了,顺手改一下

location ~ .php$ {

root html;

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/$fastcgi_script_name;

include fastcgi_params;

}

方法二 安装nginx

yum install nginx

启动nginx,并设置为开机启动

systemctl start nginx

systemctl enable nginx

vim /etc/nginx/conf.d/default.conf

5.在 /usr/share/nginx/html中新建一个test.php

访问即可看到php页面

修改完成配置记得启动apache 和php-fpm 哦!

九.负载配置

upstream site{

server 172.16.170.138;

server 172.16.170.139;

}

server {

listen 80;

server_name localhost;

#charset koi8-r;

#access_log /var/log/nginx/log/host.access.log main;

location / {

root /usr/share/nginx/html;

index index.html index.htm;

proxy_pass ;

}

apache 默认目录 /var/www/html

nginx 默认目录 /usr/share/nginx/html

升级php版本

centos7 默认安装php是5.4

查看yum的可安装的php版本列表

yum provides php

开始升级PHP更新源:

rpm -Uvh

rpm -Uvh

yum remove php-common -y #移除系统自带的php-common

php72版本

yum install -y php72w php72w-opcache php72w-xml php72w-mcrypt php72w-gd php72w-devel php72w-mysql php72w-intl php72w-mbstring

php56版本

yum install -y php56w php56w-opcache php56w-xml php56w-mcrypt php56w-gd php56w-devel php56w-mysql php56w-intl php56w-mbstring #安装依赖包

查看php版本

php -v

安装php fpm:

yum install php72w-fpm

yum provides php-fpm #因为我是准备搭建lnmp,所以安装php-fpm,这里会提示多个安装源,选择5.6版本的安装就可以了

yum install php56w-fpm-5.6.31-1.w7.x86_64 -y

systemctl start php-fpm.service 【启动】

systemctl enable php-fpm.service【开机自启动】

CentOS yum有时出现“Could not retrieve mirrorlist ”的解决办法——resolv.conf的配置

原因:没有配置resolv.conf

解决方法:

到/etc目录下配置resolv.conf加入nameserver IP,如:

nameserver 8.8.8.8

nameserver 8.8.4.4

search localdomain

保存再次运行上面的命令就可以。

nginx目录 : /usr/share/nginx/html

/etc/nginx/conf.d/default.conf nginx配置目录

apache目录 : /var/www/html

/etc/httpd/conf/httpd.conf apache配置文件

nginx 配置域名

cd /etc/nginx

cp default.conf imooc.conf

修改server_name imooc.test.com 以及项目目录

配置虚拟域名 windows 访问需要在host增加 linuxip

ServerName

DocumentRoot "/var/www/html/learnlaravel/public"

Options Indexes FollowSymLinks

AllowOverride All

Require all granted

关闭防火墙

setenforce 0

几种常见的PHP超时处理方法

【Web服务器超时处理】

[ Apache ]

一般在性能很高的情况下,缺省所有超时配置都是30秒,但是在上传文件,或者网络速度很慢的情况下,那么可能触发超时操作。

目前apachefastcgiphp-fpm模式下有三个超时设置:

fastcgi超时设置:

修改的fastcgi连接配置,类似如下:

复制代码 代码如下:

IfModulemod_fastcgi.c

FastCgiExternalServer/home/forum/apache/apache_php/cgi-bin/php-cgi-socket/home/forum/php5/etc/php-fpm.sock

ScriptAlias/fcgi-bin/"/home/forum/apache/apache_php/cgi-bin/"

AddHandlerphp-fastcgi.php

Actionphp-fastcgi/fcgi-bin/php-cgi

AddTypeapplication/x-

/IfModule

缺省配置是30s,如果需要定制自己的配置,需要修改配置,比如修改为100秒:(修改后重启apache):

复制代码 代码如下:

IfModulemod_fastcgi.c

FastCgiExternalServer/home/forum/apache/apache_php/cgi-bin/php-cgi-socket/home/forum/php5/etc/php-fpm.sock-idle-timeout100

ScriptAlias/fcgi-bin/"/home/forum/apache/apache_php/cgi-bin/"

AddHandlerphp-fastcgi.php

Actionphp-fastcgi/fcgi-bin/php-cgi

AddTypeapplication/x-

/IfModule

如果超时会返回500错误,断开跟后端php服务的连接,同时记录一条apache错误日志:

[ThuJan2718:30:152011][error][client10.81.41.110]FastCGI:commwithserver"/home/forum/apache/apache_php/cgi-bin/php-cgi"aborted:idletimeout(30sec)

[ThuJan2718:30:152011][error][client10.81.41.110]FastCGI:incompleteheaders(0bytes)receivedfromserver"/home/forum/apache/apache_php/cgi-bin/php-cgi"

其他fastcgi配置参数说明:

复制代码 代码如下:

IdleTimeout发呆时限

ProcessLifeTime一个进程的最长生命周期,过期之后无条件kill

MaxProcessCount最大进程个数

DefaultMinClassProcessCount每个程序启动的最小进程个数

DefaultMaxClassProcessCount每个程序启动的最大进程个数

IPCConnectTimeout程序响应超时时间

IPCCommTimeout与程序通讯的最长时间,上面的错误有可能就是这个值设置过小造成的

MaxRequestsPerProcess每个进程最多完成处理个数,达成后自杀

[ Lighttpd ]

配置:lig

Lighttpd配置中,关于超时的参数有如下几个(篇幅考虑,只写读超时,写超时参数同理):

主要涉及选项:

server.max-keep-alive-idle=5

server.max-read-idle=60

server.read-timeout=0

server.max-connection-idle=360

复制代码 代码如下:

#每次keep-alive的最大请求数,默认值是16

server.max-keep-alive-requests=100

#keep-alive的最长等待时间,单位是秒,默认值是5

server.max-keep-alive-idle=1200

#lighttpd的work子进程数,默认值是0,单进程运行

server.max-worker=2

#限制用户在发送请求的过程中,最大的中间停顿时间(单位是秒),

#如果用户在发送请求的过程中(没发完请求),中间停顿的时间太长,lighttpd会主动断开连接

#默认值是60(秒)

server.max-read-idle=1200

#限制用户在接收应答的过程中,最大的中间停顿时间(单位是秒),

#如果用户在接收应答的过程中(没接完),中间停顿的时间太长,lighttpd会主动断开连接

#默认值是360(秒)

server.max-write-idle=12000

#读客户端请求的超时限制,单位是秒,配为0表示不作限制

#设置小于max-read-idle时,read-timeout生效

server.read-timeout=0

#写应答页面给客户端的超时限制,单位是秒,配为0表示不作限制

#设置小于max-write-idle时,write-timeout生效

server.write-timeout=0

#请求的处理时间上限,如果用了mod_proxy_core,那就是和后端的交互时间限制,单位是秒

server.max-connection-idle=1200

说明:

对于一个keep-alive连接上的连续请求,发送第一个请求内容的最大间隔由参数max-read-idle决定,从第二个请求起,发送请求内容的最大间隔由参数max-keep-alive-idle决定。请求间的间隔超时也由max-keep-alive-idle决定。发送请求内容的总时间超时由参数read-timeout决定。Lighttpd与后端交互数据的超时由max-connection-idle决定。

延伸阅读:

[ Nginx ]

配置:nf

复制代码 代码如下:

http{

#Fastcgi:(针对后端的fastcgi生效,fastcgi不属于proxy模式)

fastcgi_connect_timeout5;#连接超时

fastcgi_send_timeout10; #写超时

fastcgi_read_timeout10;#读取超时

#Proxy:(针对proxy/upstreams的生效)

proxy_connect_timeout15s;#连接超时

proxy_read_timeout24s;#读超时

proxy_send_timeout10s; #写超时

}

说明:

Nginx 的超时设置倒是非常清晰容易理解,上面超时针对不同工作模式,但是因为超时带来的问题是非常多的。

延伸阅读:

ml

ml

ml

【PHP本身超时处理】

[ PHP-fpm ]

配置:nf

复制代码 代码如下:

?xmlversion="1.0"?

configuration

//...

Setsthelimitonthenumberofsimultaneousrequeststhatwillbeserved.

EquivalenttoApacheMaxClientsdirective.

EquivalenttoPHP_FCGI_CHILDRENenvironmentinoriginalphp.fcgi

Usedwithanypm_style.

#php-cgi的进程数量

valuename="max_children"128/value

Thetimeout(inseconds)forservingasinglerequestafterwhichtheworkerprocesswillbeterminated

Shouldbeusedwhen'max_execution_time'inioptiondoesnotstopscriptexecutionforsomereason

'0s'means'off'

#php-fpm 请求执行超时时间,0s为永不超时,否则设置一个 Ns 为超时的秒数

valuename="request_terminate_timeout"0s/value

Thetimeout(inseconds)forservingofsinglerequestafterwhichaphpbacktracewillbedumpedtoslow.logfile

'0s'means'off'

valuename="request_slowlog_timeout"0s/value

/configuration

说明:

在php.ini中,有一个参数max_execution_time可以设置PHP脚本的最大执行时间,但是,在php-cgi(php-fpm)中,该参数不会起效。真正能够控制PHP脚本最大执行时:

valuename="request_terminate_timeout"0s/value

就是说如果是使用mod_php5.so的模式运行max_execution_time是会生效的,但是如果是php-fpm模式中运行时不生效的。

延伸阅读:

[ PHP ]

配置:php.ini

选项:

max_execution_time=30

或者在代码里设置:

ini_set("max_execution_time",30);

set_time_limit(30);

说明:

对当前会话生效,比如设置0一直不超时,但是如果php的safe_mode打开了,这些设置都会不生效。

效果一样,但是具体内容需要参考php-fpm部分内容,如果php-fpm中设置了request_terminate_timeout的话,那么max_execution_time就不生效。

【后端接口访问超时】

【HTTP访问】

一般我们访问HTTP方式很多,主要是:curl,socket,file_get_contents()等方法。

如果碰到对方服务器一直没有响应的时候,我们就悲剧了,很容易把整个服务器搞死,所以在访问http的时候也需要考虑超时的问题。

[ CURL 访问HTTP]

CURL 是我们常用的一种比较靠谱的访问HTTP协议接口的lib库,性能高,还有一些并发支持的功能等。

CURL:

curl_setopt($ch,opt)可以设置一些超时的设置,主要包括:

*(重要)CURLOPT_TIMEOUT设置cURL允许执行的最长秒数。

*(重要)CURLOPT_TIMEOUT_MS设置cURL允许执行的最长毫秒数。(在cURL7.16.2中被加入。从PHP5.2.3起可使用。)

CURLOPT_CONNECTTIMEOUT在发起连接前等待的时间,如果设置为0,则无限等待。

CURLOPT_CONNECTTIMEOUT_MS尝试连接等待的时间,以毫秒为单位。如果设置为0,则无限等待。在cURL7.16.2中被加入。从PHP5.2.3开始可用。

CURLOPT_DNS_CACHE_TIMEOUT设置在内存中保存DNS信息的时间,默认为120秒。

curl普通秒级超时:

$ch=curl_init();

curl_setopt($ch,CURLOPT_URL,$url);

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

curl_setopt($ch,CURLOPT_TIMEOUT,60);//只需要设置一个秒的数量就可以

curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);

curl_setopt($ch,CURLOPT_USERAGENT,$defined_vars['HTTP_USER_AGENT']);

curl普通秒级超时使用:

curl_setopt($ch,CURLOPT_TIMEOUT,60);

curl如果需要进行毫秒超时,需要增加:

curl_easy_setopt(curl,CURLOPT_NOSIGNAL,1L);

或者是:

curl_setopt($ch,CURLOPT_NOSIGNAL,true);是可以支持毫秒级别超时设置的

curl一个毫秒级超时的例子:

复制代码 代码如下:

?php

if(!isset($_GET['foo'])){

//Client

$ch=curl_init('');

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

curl_setopt($ch,CURLOPT_NOSIGNAL,1);//注意,毫秒超时一定要设置这个

curl_setopt($ch,CURLOPT_TIMEOUT_MS,200);//超时毫秒,cURL7.16.2中被加入。从PHP5.2.3起可使用

$data=curl_exec($ch);

$curl_errno=curl_errno($ch);

$curl_error=curl_error($ch);

curl_close($ch);

if($curl_errno0){

echo"cURLError($curl_errno):$curl_errorn";

}else{

echo"Datareceived:$datan";

}

}else{

//Server

sleep(10);

echo"Done.";

}

?

其他一些技巧:

1. 按照经验总结是:cURL版本=libcurl/7.21.0版本,毫秒级超时是一定生效的,切记。

2. curl_multi的毫秒级超时也有问题。。单次访问是支持ms级超时的,curl_multi并行调多个会不准

[流处理方式访问HTTP]

除了curl,我们还经常自己使用fsockopen、或者是file操作函数来进行HTTP协议的处理,所以,我们对这块的超时处理也是必须的。

一般连接超时可以直接设置,但是流读取超时需要单独处理。

自己写代码处理:

复制代码 代码如下:

$tmCurrent=gettimeofday();

$intUSGone=($tmCurrent['sec']-$tmStart['sec'])*1000000

+($tmCurrent['usec']-$tmStart['usec']);

if($intUSGone$this-_intReadTimeoutUS){

returnfalse;

}

或者使用内置流处理函数stream_set_timeout()和stream_get_meta_data()处理:

复制代码 代码如下:

?php

//Timeoutinseconds

$timeout=5;

$fp=fsockopen("",80,$errno,$errstr,$timeout);

if($fp){

fwrite($fp,"GET/HTTP/1.0rn");

fwrite($fp,"Host:rn");

fwrite($fp,"Connection:Closernrn");

stream_set_blocking($fp,true);//重要,设置为非阻塞模式

stream_set_timeout($fp,$timeout);//设置超时

$info=stream_get_meta_data($fp);

while((!feof($fp))(!$info['timed_out'])){

$data.=fgets($fp,4096);

$info=stream_get_meta_data($fp);

ob_flush;

flush();

}

if($info['timed_out']){

echo"ConnectionTimedOut!";

}else{

echo$data;

}

}

file_get_contents超时:

复制代码 代码如下:

?php

$timeout=array(

'http'=array(

'timeout'=5//设置一个超时时间,单位为秒

)

);

$ctx=stream_context_create($timeout);

$text=file_get_contents("",0,$ctx);

?

fopen超时:

复制代码 代码如下:

?php

$timeout=array(

'http'=array(

'timeout'=5//设置一个超时时间,单位为秒

)

);

$ctx=stream_context_create($timeout);

if($fp=fopen("","r",false,$ctx)){

while($c=fread($fp,8192)){

echo$c;

}

fclose($fp);

}

?

【MySQL】

php中的mysql客户端都没有设置超时的选项,mysqli和mysql都没有,但是libmysql是提供超时选项的,只是我们在php中隐藏了而已。

那么如何在PHP中使用这个操作捏,就需要我们自己定义一些MySQL操作常量,主要涉及的常量有:

MYSQL_OPT_READ_TIMEOUT=11;

MYSQL_OPT_WRITE_TIMEOUT=12;

这两个,定义以后,可以使用options设置相应的值。

不过有个注意点,mysql内部实现:

1.超时设置单位为秒,最少配置1秒

2.但mysql底层的read会重试两次,所以实际会是3秒

重试两次+ 自身一次=3倍超时时间,那么就是说最少超时时间是3秒,不会低于这个值,对于大部分应用来说可以接受,但是对于小部分应用需要优化。

查看一个设置访问mysql超时的php实例:

复制代码 代码如下:

?php

//自己定义读写超时常量

if(!defined('MYSQL_OPT_READ_TIMEOUT')){

define('MYSQL_OPT_READ_TIMEOUT',11);

}

if(!defined('MYSQL_OPT_WRITE_TIMEOUT')){

define('MYSQL_OPT_WRITE_TIMEOUT',12);

}

//设置超时

$mysqli=mysqli_init();

$mysqli-options(MYSQL_OPT_READ_TIMEOUT,3);

$mysqli-options(MYSQL_OPT_WRITE_TIMEOUT,1);

//连接数据库

$mysqli-real_connect("localhost","root","root","test");

if(mysqli_connect_errno()){

printf("Connectfailed:%s/n",mysqli_connect_error());

exit();

}

//执行查询sleep1秒不超时

printf("Hostinformation:%s/n",$mysqli-host_info);

if(!($res=$mysqli-query('selectsleep(1)'))){

echo"query1error:".$mysqli-error."/n";

}else{

echo"Query1:querysuccess/n";

}

//执行查询sleep9秒会超时

if(!($res=$mysqli-query('selectsleep(9)'))){

echo"query2error:".$mysqli-error."/n";

}else{

echo"Query2:querysuccess/n";

}

$mysqli-close();

echo"closemysqlconnection/n";

?

延伸阅读:

【Memcached】

[PHP扩展]

php_memcache客户端:

连接超时:boolMemcache::connect(string$host[,int$port[,int$timeout]])

在get和set的时候,都没有明确的超时设置参数。

libmemcached客户端:在php接口没有明显的超时参数。

说明:所以说,在PHP中访问Memcached是存在很多问题的,需要自己hack部分操作,或者是参考网上补丁。

[CC++访问Memcached]

客户端:libmemcached客户端

说明:memcache超时配置可以配置小点,比如5,10个毫秒已经够用了,超过这个时间还不如从数据库查询。

下面是一个连接和读取set数据的超时的C++示例:

复制代码 代码如下:

//创建连接超时(连接到Memcached)

memcached_st*MemCacheProxy::_create_handle()

{

memcached_st*mmc=NULL;

memcached_return_tprc;

if(_mpool!=NULL){//getfrompool

mmc=memcached_pool_pop(_mpool,false,prc);

if(mmc==NULL){

__LOG_WARNING__("MemCacheProxy","gethandlefrompoolerror[%d]",(int)prc);

}

returnmmc;

}

memcached_st*handle=memcached_create(NULL);

if(handle==NULL){

__LOG_WARNING__("MemCacheProxy","create_handleerror");

returnNULL;

}

//设置连接/读取超时

memcached_behavior_set(handle,MEMCACHED_BEHAVIOR_HASH,MEMCACHED_HASH_DEFAULT);

memcached_behavior_set(handle,MEMCACHED_BEHAVIOR_NO_BLOCK,_noblock);//参数MEMCACHED_BEHAVIOR_NO_BLOCK为1使超时配置生效,不设置超时会不生效,关键时候会悲剧的,容易引起雪崩

memcached_behavior_set(handle,MEMCACHED_BEHAVIOR_CONNECT_TIMEOUT,_connect_timeout);//连接超时

memcached_behavior_set(handle,MEMCACHED_BEHAVIOR_RCV_TIMEOUT,_read_timeout);//读超时

memcached_behavior_set(handle,MEMCACHED_BEHAVIOR_SND_TIMEOUT,_send_timeout);//写超时

memcached_behavior_set(handle,MEMCACHED_BEHAVIOR_POLL_TIMEOUT,_poll_timeout);

//设置一致hash

//memcached_behavior_set_distribution(handle,MEMCACHED_DISTRIBUTION_CONSISTENT);

memcached_behavior_set(handle,MEMCACHED_BEHAVIOR_DISTRIBUTION,MEMCACHED_DISTRIBUTION_CONSISTENT);

memcached_returnrc;

for(uinti=0;i_server_count;i++){

rc=memcached_server_add(handle,_ips[i],_ports[i]);

if(MEMCACHED_SUCCESS!=rc){

__LOG_WARNING__("MemCacheProxy","addserver[%s:%d]failed.",_ips[i],_ports[i]);

}

}

_mpool=memcached_pool_create(handle,_min_connect,_max_connect);

if(_mpool==NULL){

__LOG_WARNING__("MemCacheProxy","create_poolerror");

returnNULL;

}

mmc=memcached_pool_pop(_mpool,false,prc);

if(mmc==NULL){

__LOG_WARNING__("MyMemCacheProxy","gethandlefrompoolerror[%d]",(int)prc);

}

//__LOG_DEBUG__("MemCacheProxy","gethandle[%p]",handle);

returnmmc;

}

//设置一个key超时(set一个数据到memcached)

boolMemCacheProxy::_add(memcached_st*handle,unsignedint*key,constchar*value,intlen,unsignedinttimeout)

{

memcached_returnrc;

chartmp[1024];

snprintf(tmp,sizeof(tmp),"%u#%u",key[0],key[1]);

//有个timeout值

rc=memcached_set(handle,tmp,strlen(tmp),(char*)value,len,timeout,0);

if(MEMCACHED_SUCCESS!=rc){

returnfalse;

}

returntrue;

}

//Memcache读取数据超时(没有设置)

libmemcahed源码中接口定义:

LIBMEMCACHED_APIchar*memcached_get(memcached_st*ptr,constchar*key,size_tkey_length,size_t*value_length,uint32_t*flags,memcached_return_t*error);

LIBMEMCACHED_APImemcached_return_tmemcached_mget(memcached_st*ptr,constchar*const*keys,constsize_t*key_length,size_tnumber_of_keys);

从接口中可以看出在读取数据的时候,是没有超时设置的。

延伸阅读:

【如何实现超时】

程序中需要有超时这种功能,比如你单独访问一个后端Socket模块,Socket模块不属于我们上面描述的任何一种的时候,它的协议也是私有的,那么这个时候可能需要自己去实现一些超时处理策略,这个时候就需要一些处理代码了。

[PHP中超时实现]

一、初级:最简单的超时实现 (秒级超时)

思路很简单:链接一个后端,然后设置为非阻塞模式,如果没有连接上就一直循环,判断当前时间和超时时间之间的差异。

phpsocket中实现原始的超时:(每次循环都当前时间去减,性能会很差,cpu占用会较高)

复制代码 代码如下:

?

$host="127.0.0.1";

$port="80";

$timeout=15;//timeoutinseconds

$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)

ordie("Unabletocreatesocketn");

socket_set_nonblock($socket) //务必设置为阻塞模式

ordie("Unabletosetnonblockonsocketn");

$time=time();

//循环的时候每次都减去相应值

while(!@socket_connect($socket,$host,$port))//如果没有连接上就一直死循环

{

$err=socket_last_error($socket);

if($err==115||$err==114)

{

if((time()-$time)=$timeout)//每次都需要去判断一下是否超时了

{

socket_close($socket);

die("Connectiontimedout.n");

}

sleep(1);

continue;

}

die(socket_strerror($err)."n");

}

socket_set_block($this-socket)//还原阻塞模式

ordie("Unabletosetblockonsocketn");

?

二、升级:使用PHP自带异步IO去实现(毫秒级超时)

说明:

异步IO:异步IO的概念和同步IO相对。当一个异步过程调用发出后,调用者不能立刻得到结果。实际处理这个调用的部件在完成后,通过状态、通知和回调来通知调用者。异步IO将比特分成小组进行传送,小组可以是8位的1个字符或更长。发送方可以在任何时刻发送这些比特组,而接收方从不知道它们会在什么时候到达。

多路复用:复用模型是对多个IO操作进行检测,返回可操作集合,这样就可以对其进行操作了。这样就避免了阻塞IO不能随时处理各个IO和非阻塞占用系统资源的确定。

使用socket_select()实现超时

socket_select(...,floor($timeout),ceil($timeout*1000000));

select的特点:能够设置到微秒级别的超时!

使用socket_select()的超时代码(需要了解一些异步IO编程的知识去理解)

复制代码 代码如下:

编程 调用类 编程#

?php

$server=newServer;

$client=newClient;

for(;;){

foreach($select-can_read(0)as$socket){

if($socket==$client-socket){

//NewClientSocket

$select-add(socket_accept($client-socket));

}

else{

//there'ssomethingtoreadon$socket

}

}

}

?

编程 异步多路复用IO 超时连接处理类 编程

?php

classselect{

var$sockets;

functionselect($sockets){

$this-sockets=array();

foreach($socketsas$socket){

$this-add($socket);

}

}

functionadd($add_socket){

array_push($this-sockets,$add_socket);

}

functionremove($remove_socket){

$sockets=array();

foreach($this-socketsas$socket){

if($remove_socket!=$socket)

$sockets[]=$socket;

}

$this-sockets=$sockets;

}

functioncan_read($timeout){

$read=$this-sockets;

socket_select($read,$write=NULL,$except=NULL,$timeout);

return$read;

}

functioncan_write($timeout){

$write=$this-sockets;

socket_select($read=NULL,$write,$except=NULL,$timeout);

return$write;

}

}

?

[CC++中超时实现]

一般在LinuxC/C++中,可以使用:alarm()设置定时器的方式实现秒级超时,或者:select()、poll()、epoll()之类的异步复用IO实现毫秒级超时。也可以使用二次封装的异步io库(libevent,libev)也能实现。

一、使用alarm中用信号实现超时 (秒级超时)

说明:Linux内核connect超时通常为75秒,我们可以设置更小的时间如10秒来提前从connect中返回。这里用使用信号处理机制,调用alarm,超时后产生SIGALRM信号(也可使用select实现)

用alarym秒级实现 connect设置超时代码示例:

复制代码 代码如下:

//信号处理函数

staticvoidconnect_alarm(intsigno)

{

debug_printf("SignalHandler");

return;

}

//alarm超时连接实现

staticvoidconn_alarm()

{

Sigfunc*sigfunc;//现有信号处理函数

sigfunc=signal(SIGALRM,connect_alarm);//建立信号处理函数connect_alarm,(如果有)保存现有的信号处理函数

inttimeout=5;

//设置闹钟

if(alarm(timeout)!=0){

//...闹钟已经设置处理

}

//进行连接操作

if(connect(m_Socket,(structsockaddr*)addr,sizeof(addr))0){

if(errno==EINTR){//如果错误号设置为EINTR,说明超时中断了

debug_printf("Timeout");

腾讯云window系统怎么配置php环境

从一开始选购到配置的整个过程,需要一个 win中的php面板就能够轻松搭建了。

win服务器我建议从2核4g起步,低于这个配置都会卡顿、缓慢等。

买完后会给你发远程账号密码,拿到后使用远程桌面登陆程序,就可以成功连接到 server服务器上了。然后在服务器上就跟你自己的本地电脑一样,开始搭建环境,部署网站了。

以前人都是自己手动配置 IIS,很麻烦还容易出错。现在有了一键php包,就方便多了。具体安装配置过程比较多,或者你去看看快速配置 Windows 云服务器文档,那里面写的很详细的,比我说的这些更具体。

php-mysql模块已安装,phpinfo()却显示不出拓展

编辑php.ini,去掉需要添加模块的注释,例如;extension=php_mysql.dll改成extension=php_mysql.dll,重启php


网页名称:php-fpm连接数据库 php7连接数据库
文章网址:http://cxhlcq.com/article/dooiscp.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部