一、PHP加速器原理

    PHP加速器是一个为了提高PHP执行效率,从而缓存起PHP的操作码,这样PHP后面执行就不用解析转换了,可以直接调用PHP操作码,这样速度上就提高了不少。

Apache中使用mod_php的请求、响应执行流程:

  1. Apache接收请求。

  2. Apache传递请求给mod_php。

  3. mod_php定位磁盘文件,并加载到内存中。

  4. mod_php编译源代码成为opcode树。

  5. mod_php执行opcode树。

    PHP加速器相应的就是第四步,它的目的就是防止PHP每次请求都重复编译PHP代码,因为在高访问量的网站上,大量的编译往往没有执行速度快呢?所以这里面有个瓶颈就是PHP的重复编译既影响了速度又加载了服务器负载,为了解决此问题,PHP加速器就这样诞生了。

    每一次的请求都会反复执行Parse-Compile-Execute,而在实际中,服务端的php代码一般都不会发生变化,我们每次请求都要反复执行一些没有必要的操作,这直接影响了PHP的性能,我们到这里肯定会想到为什么不用缓存了?目前已经有很多成熟的缓存机制,用在PHP代码的执行方面应该绰绰有余,就算我们的PHP代码会发生变化,我们也可以用一种成熟的算法来保证代码改变后重新缓存,这一切都不是问题。是的,这就是PHP加速器的工作原理:

二、几种流行的php加速器的安装与配置

1、安装配置APC

APC全称是Alternative PHP Cache,它是PHP PECL中的一个扩展。

WINDOWS下安装

第一步:下载php_apc.dll 在http://pecl.php.net/package/apc 要与php版本对应 将php_apc.dll放入你的ext目录

第二步:让php.ini支持apc扩展模块。 然后打开php.ini 加入:

extension=php_apc.dll

apc.rfc1867 = on

apc.max_file_size = 100M

upload_max_filesize = 100M

post_max_size = 100M

//以上参数可自己定义

第三步:检查是否支持PHP APC apc_store apc_fetch PHP APC 配置参数 把相关的配置放在一起解释。

apc.enabled=1 apc.enabled默认值是1,你可设成0禁用APC。如果你设置为0的时候,同样把extension=apc.so也注释掉(这样可以节约内存资源)。一旦启用了APC功能,则会缓存Opcodes到共享内存。

apc.shm_segments = 1

总结 1,使用Spinlocks锁机制,能够达到最佳性能。

2,APC提供了apc.php,用于监控与管理APC缓存。不要忘记修改管理员名和密码

3,APC默认通过mmap匿名映射创建共享内存,缓存对象都存放在这块”大型”的内存空间。由APC自行管理该共享内存

4,我们需要通过统计调整apc.shm_size、apc.num_files_hints、apc.user_entries_hint的值。直到最佳

5,好吧,我承认apc.stat = 0 可以获得更佳的性能。要我做什么都可以接受.

6,PHP预定义常量,可以使用apc_define_constants()函数。不过据APC开发者介绍说pecl hidef性能更佳,抛异define吧,它是低效的。

7,函数apc_store(),对于系统设置等PHP变量,生命周期是整个应用(从httpd守护进程直到httpd守护进程关闭),使用APC比Memcached会更好。必竟不要经过网络传输协议tcp。

8,APC不适于通过函数apc_store()缓存频繁变更的用户数据,会出现一些奇异现象。

Linux下安装

$ wget http://pecl.php.net/get/APC-3.0.19.tgz$ tar xvzf APC-3.0.19.tgz$ cd APC-3.0.19/APC-3.0.19$ /usr/local/php/bin/phpize$ ./configure --enable-apc --enable-apc-mmap --with-php-config=/usr/local/php/bin/php-config$ make$ make install

下面我们再配置APC,因为我的PECL扩展路径改变了,所以我得移动下编译好的文件:

$
mv 
/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/apc
.so 
/usr/local/php/lib/php/extensions/PECL

然后我们再编辑php.ini文件进行配置,请把下面的代码加入到php.ini中即可:

extension_dir = "/usr/local/php/lib/php/extensions/PECL"extension = apc.so; APCapc.enabled = 1apc.shm_segments = 1apc.shm_size = 64apc.optimization = 1apc.num_files_hint = 0apc.ttl = 0apc.gc_ttl = 3600apc.cache_by_default = on

这样重启apache就会在phpinfo()信息中显示。

       

2、安装配置eAccelerator

   eAccelerator的前身其实是truck-mmcache,因为开发truk-mmcache的人被Zend给招安了,所以开发eAccelerator的人继承了truk-mmcache的一些特性,设计出eAccelerator加速器。安装如下:

$wget http://jaist.dl.sourceforge.net/sourceforge/eaccelerator/eaccelerator-0.9.5.tar.bz2$ tar -jxf eaccelerator-0.9.5.tar.bz2$ cd eaccelerator-0.9.5$ /usr/local/php/bin/phpize$./configure –enable-eaccelerator=shared –with-php-config=/usr/local/php/bin/php-config$ make$ make install$ mv /usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so /usr/local/php/lib/php/extensions/PECL

将下面代码加入php.ini文件中

extension = eaccelerator.so; eAcceleratoreaccelerator.shm_size = "16"eaccelerator.cache_dir = "/tmp/eaccelerator"eaccelerator.enable = "1"eaccelerator.optimizer = "1"eaccelerator.check_mtime = "1"eaccelerator.debug = "0"eaccelerator.filter = ""eaccelerator.shm_max = "0"eaccelerator.shm_ttl = "0"eaccelerator.prune_period = "0"eaccelerator.shm_only = "0"eaccelerator.compress = "1"eaccelerator.compress_level = "9"创建缓存目录,重启apache$mkdir /tmp/eaccelerator$chmod 777 /tmp/eaccelerator$/usr/local/apache/apachectl restart

在phpinfo()检查是否安装成功.

3、安装配置XCache

    XCache是国人自己开发的东西,性能比早期的eAccelerator加速器要优良。

$wget http://xcache.lighttpd.net/pub/Releases/1.2.2/xcache-1.2.2.tar.gz$tar xvzf xcache-1.2.2.tar.gz$cd xcache-1.2.2$/usr/local/php/bin/phpize$./configure –enable-xcache –enable-xcache-coverager –with-php-config=/usr/local/php/php-config$make$make install$mv /usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/xcache.so /usr/local/php/lib/php/extensions/PECL

在php.ini添加配置信息:

extension = xcache.so; xcachexcache.admin.user = "admin"xcache.admin.pass = "(执行) echo ’(你的密码)’|md5sum(得出的密文)";xcache.size = 24Mxcache.shm_scheme = "mmap"xcache.count = 2xcache.slots = 8kxcache.ttl = 0xcache.gc_interval = 0xcache.var_size = 8Mxcache.var_count = 1xcache.var_slots = 8kxcache.var_ttl = 0xcache.var_maxttl = 0xcache.var_gc_interval = 300xcache.test = Offxcache.readonly_protection = Onxcache.mmap_path = "/tmp/xcache"xcache.coredump_directory = ""xcache.cacher = Onxcache.stat = Onxcache.optimizer = Off;xcache.coverager = Onxcache.coveragedump_directory = ""  创建缓存目录,重启apache$mkdir /tmp/xcache$chmod 777 /tmp/xcache$/usr/local/apache/bin/apachectl restart

4、Opcache简介

新一代PHP加速器,由Zend公司研发,其实现原理与Xcache类似,都是把PHP执行后的数据缓冲到内存中从而避免重复的编译过程,能够直接使用缓冲区已编译的代码从而提高速度,降低服务器负载,但性能却比Xcache更加优越。

安装Opcache

wget http://pecl.php.net/get/zendopcache-7.0.2.tgztar xzf zendopcache-7.0.2.tgzcd zendopcache-7.0.2/usr/local/php/bin/phpize./configure --with-php-config=/usr/local/php/bin/php-configmakemake install# 配置文件设置,可直接在php.ini的最后添加如下内容,但在此在PHP配置文件的扫描目录php.d下配置新文件opcache.ini,易于管理,php-config-scan-dir是在编译安装PHP时定义的# vi /etc/php.d/opcache.ini[opcache]zend_extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/opcache.soopcache.memory_consumption=128 # 分配的内存大小,单位MB,即能够存储多少预编译的PHP代码opcache.interned_strings_buffer=8 # interned字符串占内存大小,单位MBopcache.max_accelerated_files=4000 # 允许缓存的文件最大数量opcache.revalidate_freq=60 # 多长时间检查文件时间戳,以改变共享内存分配,单位为sopcache.fast_shutdown=1 # 是否开启快速关闭队列功能,1为开启opcache.enable_cli=1 # 允许缓存CLI下的PHP程序#检查模块安装成功:/usr/local/php/bin/php -m |grep -i opcache

zabbix监控PHP  APC缓存                

1.监控原理

将APC源码包中的apc.php放到/usr/local/bin/ 目录下

添加nginx子配置文件php-apc_status.conf

server{        listen      80;        server_name 127.0.0.1;        access_log  off;        client_max_body_size 5m;         autoindex off;        location / {            root  /usr/local/zabbix/bin/;            index index.php;            autoindex off;        }         location ~ \.php$ {            root           /usr/local/zabbix/bin/;            fastcgi_pass   127.0.0.1:9000;            fastcgi_index  index.php;            fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;            include        fastcgi_params;        }}

通过links这个命令可以在命令行下方为HTML页面

yum -y install links

links 127.0.0.1/apc.php -dump 2>/dev/null

2.编写PHP-APC状态信息获取脚本

php-apc_status.sh

#!/bin/bash#This script is used to get php apc cache data from  apc.php page#you need put nginx sub-config file php-apc_status.conf under conf/conf.d/ directoryapc_metric=$1apc_status_url="http://127.0.0.1/apc.php"apc_status_file=/tmp/php-apc_status.txt/usr/bin/links $apc_status_url -dump 2>/dev/null > $apc_status_file#echo $apc_status #we need to convert GBytes,Mbytes,KBytes to Bytes#echo "308.345 * 1024 * 1024 * 1024"|bc|cut -f1 -d.#331082922721convert_size() {  value=$1  unit=$2   echo $value | grep -E '^[0-9.]+$' 2>&1 > /dev/null  if [ $? -ne 0 ]; then    echo "$value is not number"    exit 1  fi   case $unit in    Bytes)          echo "$value"        ;;   KBytes)           echo "$value * 1024" | bc | cut -f1 -d.         ;;   MBytes)           echo "$value * 1024 * 1024" | bc | cut -f1 -d.         ;;   GBytes)           echo "$value * 1024 * 1024 * 1024" | bc | cut -f1 -d.         ;;  esac} #get apc metric data case $apc_metric in            version)                  cat $apc_status_file|grep "APC Version"|awk '{print $3}'                 ;; cached_files_count)                  cat $apc_status_file|grep "Cached Files"|head -1|awk '{print $3}'                 ;;  cached_files_size)                  convert_size   $(cat $apc_status_file|grep "Cached Files"|awk '{print $4 " " $5}'|sed -e 's/(//' -e 's/)//')                         ;;               hits)                  cat $apc_status_file|grep  "Hits"|head -1|awk '{print $2}'                  ;;              phits)                  cat $apc_status_file|grep "Free"|head -1|awk '{print $7}'|sed -e 's/(//' -e s'/)//' -e 's/%//'                 ;;             misses)                  cat $apc_status_file|grep  "Misses"|head -1|awk '{print $2}'                 ;;       request_rate)                  cat $apc_status_file|grep  "Request Rate"|head -1|awk '{print $5}'                 ;;                   hit_rate)                  cat $apc_status_file|grep "Hit Rate"|head -1|awk '{print $3}'                 ;;          miss_rate)                  cat $apc_status_file|grep "Miss Rate"|head -1| awk '{print $3}'                 ;;        insert_rate)                  cat $apc_status_file|grep "Insert Rate"|head -1| awk '{print $3}'                 ;;   cache_full_count)                   cat $apc_status_file|grep "Cache full count"|head -1|awk '{print $4}'                 ;;           shm_size)                   #apc.shm_size can be 400M or 2G , convert M or G to Bytes                   shm=$(cat $apc_status_file|grep "apc.shm_size"|head -1| awk '{print $2}')                   if [ $(echo "$shm"|grep 'M$') ];then                      size=$(echo $shm|sed 's/M//')                     echo "$size * 1024 * 1024"|bc                   elif [ $(echo "$shm"|grep 'G$') ];then                     size=$(echo $shm|sed 's/G//')                     echo "$size * 1024 * 1024 * 1024"|bc                   fi                 ;;                 mem_free)                              convert_size $(cat $apc_status_file|grep "Free"|head -1|awk '{print $2 " " $3}')                 ;;           mem_used)                              convert_size $(cat $apc_status_file|grep "Used"|head -1|awk '{print $2 " " $3}')                 ;;          mem_pused)                  cat $apc_status_file|grep "Used"|head -1|awk '{print $4}'|sed -e 's/(//' -e 's/)//' -e 's/%//'                 ;;                 fragmentation)                           cat $apc_status_file|grep "Fragmentation:"|head -1|awk '{print $2}'|sed -e 's/%//'                 ;;                  *)                  echo "please input the right parameter"                 ;;     esac

3.添加zabbix 子配置文件php-apc_status_zabbix.conf

UserParameter=php-apc[*],/usr/local/zabbix/bin/php-apc_status.sh $1

4.创建zabbix的PHP-APC模板