大纲

一、前言

二、环境准备

三、memcache 应用一 php与memcache

四、memcache 应用二 nginx与memcache

五、memcache 应用三 session与memcache

六、memcache 图形管理工具

注,操作系统 CentOS 6.4 x86_64,博文中所有软件请到这里下载:http://yunpan.cn/QXheiWttcavn2


一、前言

在上一篇博客中我们主要讲解了memcache的基本知识,对memcache不了解的博友可以参考一下这篇博文http://freeloda.blog.51cto.com/2033581/1289806,在这一篇博文中我们主要讲解memcache的d三应用与图形管理工具,主要内容有php结合memcache、nginx结合memcache、session与memcache、memcache图形管理工具。好了,下面我们就来具体说一下吧。

二、环境准备

1.操作系统

  • CentOS 6.4 x86_64

2.软件版本

  • memcached-1.4.15

  • libevent-2.0.21

  • php-5.4.19

  • mysql-5.6.13

  • nginx-1.4.2

3.实验拓扑

Memcache 应用详解

4.安装yum源

[[email protected] ~]# rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
[[email protected] ~]# rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

5.同步节点时间

[[email protected] ~]# ntpdate 202.120.2.101
[[email protected] ~]# ntpdate 202.120.2.101

6.安装防火墙与SELinux

[[email protected] ~]# service iptables stop   
[[email protected] ~]# chkconfig iptables off    
[[email protected] ~]# getenforce    
Disabled
[[email protected] ~]# service iptables stop   
[[email protected] ~]# chkconfig iptables off    
[[email protected] ~]# getenforce    
Disabled

7.准备LNMP环境

(1).安装并配置nginx

解压源码包

[[email protected] src]# tar xf nginx-1.4.2.tar.gz
[[email protected] src]# cd nginx-1.4.2

新建nginx用户

[[email protected] nginx]# groupadd -g 108  -r nginx
[[email protected] nginx]# useradd -u 108 -r -g 108 nginx
[[email protected] nginx]# id nginx
uid=108(nginx) gid=108(nginx) 组=108(nginx)

安装openssl-devel

[[email protected] nginx-1.4.2]# yum install -y openssl-devel

安装pcre-devel

[[email protected] nginx-1.4.2]# yum -y install pcre-devel

配置nginx编译配置文件

[[email protected] nginx-1.4.2]# ./configure \   
>   --prefix=/usr \    
>   --sbin-path=/usr/sbin/nginx \    
>   --conf-path=/etc/nginx/nginx.conf \    
>   --error-log-path=/var/log/nginx/error.log \    
>   --http-log-path=/var/log/nginx/access.log \    
>   --pid-path=/var/run/nginx/nginx.pid  \    
>   --lock-path=/var/lock/nginx.lock \    
>   --user=nginx \    
>   --group=nginx \    
>   --with-http_ssl_module \    
>   --with-http_flv_module \    
>   --with-http_stub_status_module \    
>   --with-http_gzip_static_module \    
>   --http-client-body-temp-path=/var/tmp/nginx/client/ \    
>   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \    
>   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \    
>   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \    
>   --http-scgi-temp-path=/var/tmp/nginx/scgi \    
>   --with-pcre

编译并安装nginx

[[email protected] nginx-1.4.2]# make && make install

为nginx提供SysV init脚本

[[email protected] nginx-1.4.2]# cat /etc/init.d/nginx   
#!/bin/sh    
#    
# nginx - this script starts and stops the nginx daemon    
#    
# chkconfig:   - 85 15    
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \    
#               proxy and IMAP/POP3 proxy server    
# processname: nginx    
# config:      /etc/nginx/nginx.conf    
# config:      /etc/sysconfig/nginx    
# pidfile:     /var/run/nginx.pid    
# Source function library.    
. /etc/rc.d/init.d/functions    
# Source networking configuration.    
. /etc/sysconfig/network    
# Check that networking is up.    
[ "$NETWORKING" = "no" ] && exit 0    
nginx="/usr/sbin/nginx"    
prog=$(basename $nginx)    
NGINX_CONF_FILE="/etc/nginx/nginx.conf"    
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx    
lockfile=/var/lock/subsys/nginx    
make_dirs() {    
   # make required directories    
   user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`    
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`    
   for opt in $options; do    
       if [ `echo $opt | grep '.*-temp-path'` ]; then    
           value=`echo $opt | cut -d "=" -f 2`    
           if [ ! -d "$value" ]; then    
               # echo "creating" $value    
               mkdir -p $value && chown -R $user $value    
           fi    
       fi    
   done    
}    
start() {    
    [ -x $nginx ] || exit 5    
    [ -f $NGINX_CONF_FILE ] || exit 6    
    make_dirs    
    echo -n $"Starting $prog: "    
    daemon $nginx -c $NGINX_CONF_FILE    
    retval=$?    
    echo    
    [ $retval -eq 0 ] && touch $lockfile    
    return $retval    
}    
stop() {    
    echo -n $"Stopping $prog: "    
    killproc $prog -QUIT    
    retval=$?    
    echo    
    [ $retval -eq 0 ] && rm -f $lockfile    
    return $retval    
}    
restart() {    
    configtest || return $?    
    stop    
    sleep 1    
    start    
}    
reload() {    
    configtest || return $?    
    echo -n $"Reloading $prog: "    
    killproc $nginx -HUP    
    RETVAL=$?    
    echo    
}    
force_reload() {    
    restart    
}    
configtest() {    
  $nginx -t -c $NGINX_CONF_FILE    
}    
rh_status() {    
    status $prog    
}    
rh_status_q() {    
    rh_status >/dev/null 2>&1    
}    
case "$1" in    
    start)    
        rh_status_q && exit 0    
        $1    
        ;;    
    stop)    
        rh_status_q || exit 0    
        $1    
        ;;    
    restart|configtest)    
        $1    
        ;;    
    reload)    
        rh_status_q || exit 7    
        $1    
        ;;    
    force-reload)    
        force_reload    
        ;;    
    status)    
        rh_status    
        ;;    
    condrestart|try-restart)    
        rh_status_q || exit 0    
            ;;    
    *)    
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"    
        exit 2    
esac

为此脚本赋予执行权限

[[email protected] nginx-1.4.2]# chmod +x /etc/init.d/nginx

添加至服务管理列表,并让其开机自动启动

[[email protected] nginx-1.4.2]# chkconfig --add nginx   
[[email protected] nginx-1.4.2]# chkconfig nginx on    
[[email protected] nginx-1.4.2]# chkconfig nginx --list    
nginx              0:关闭    1:关闭    2:启用    3:启用    4:启用    5:启用    6:关闭

启动nginx

[[email protected] nginx-1.4.2]# service nginx start   
正在启动 nginx:                                           [确定]

查看一下端口号    

[[email protected] nginx-1.4.2]# netstat -ntulp   
Active Internet connections (only servers)    
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name  
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      9280/nginx         
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1048/sshd          
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1124/master        
tcp        0      0 :::22                       :::*                        LISTEN      1048/sshd          
tcp        0      0 ::1:25                      :::*                        LISTEN      1124/master

测试一下

Memcache 应用详解

修改一下配置文件(修改主文档目录/data/www)

[[email protected] nginx-1.4.2]# vim /etc/nginx/nginx.conf
server {   
        listen       80;    
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {   
            root   /data/www;    
            index  index.html index.htm;    
        }
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html   
        #    
        error_page   500 502 503 504  /50x.html;    
        location = /50x.html {    
            root   html;    
        }
}

提供测试文件

[[email protected] ~]# mkdir –pv /data/www/
[[email protected] ~]# cd /data/www/
[[email protected] www]# ll
总用量 12
-rw-r--r-- 1 nginx nginx   23 8月  29 20:04 index.html
[[email protected] www]# vim index.html
<h1>www.nginx.org</h1>

重新加载一下配置

[[email protected] nginx-1.4.2]# service nginx reload   
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok    
nginx: configuration file /etc/nginx/nginx.conf test is successful    
重新载入 nginx:                                           [确定]

再次测试一下

Memcache 应用详解

好了,到这里nginx的安装与配置全部完成,下面我们来安装与配置mysql数据库。

(2).安装并配置mysql

准备数据存放的文件系统

说明:新建一个逻辑卷,并将其挂载至特定目录即可。这里假设其逻辑卷的挂载目录为/mydata,而后需要创建/mydata/data目录做为mysql数据的存放目录。

先确认下系统里是否有LVM工具,默认没有安装

[[email protected] httpd]# rpm -qa | grep lvm
[[email protected] httpd]# yum install -y lvm2

查看一下磁盘

[[email protected] ~]# fdisk -l
Disk /dev/sda: 21.5 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/Osize (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000dfceb
Device Boot      Start         End      Blocks   Id  System
/dev/sda1*           1          26      204800   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda226        1301    10240000   83  Linux
/dev/sda31301        1938     5120000   83  Linux
/dev/sda41938        2611     5405696    5  Extended
/dev/sda51939        2066     1024000   82  Linux swap / Solaris
Disk /dev/sdb: 21.5 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/Osize (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

创建逻辑分区

[[email protected] ~]# fdisk /dev/sdb
[[email protected] ~]# fdisk –l
/dev/sdb11        1306    10490413+  8e  Linux LVM #我这里是测试环境就创建了一个10G分区
[[email protected] ~]# partx -a /dev/sdb #告诉内核有关存在和磁盘上的分区的编号
[[email protected] ~]# pvcreate /dev/sdb1 ##创建物理卷
Physical volume "/dev/sdb1"successfully created
[[email protected] ~]# vgcreate myvg /dev/sdb1 #创建卷组
Volume group "myvg"successfully created
[[email protected] ~]# lvcreate -n mydata -L 5G myvg #创建一个5G的逻辑卷
Logical volume "mydata"created
[[email protected] ~]# lvs #查看一下逻辑卷
LV     VG   Attr      LSize Pool Origin Data%  Move Log Cpy%Sync Convert
mydata myvg -wi-a---- 5.00g
[[email protected] ~]# mkfs.ext4 /dev/myvg/mydata #格式化
[[email protected] ~]# mkdir /mydata #创建挂载目录
[[email protected] ~]# mount /dev/myvg/mydata /mydata/ #挂载
[[email protected] ~]# vim /etc/fstab
/dev/myvg/mydata/mydataext4defaults        0 0 #增加这一行
[[email protected] ~]# mount –a #测试挂载是否成功
[[email protected] ~]# mount #查看一下
/dev/sda2on/ typeext4 (rw)
proc on /proctypeproc(rw)
sysfs on /systypesysfs(rw)
devpts on /dev/ptstypedevpts(rw,gid=5,mode=620)
tmpfs on /dev/shmtypetmpfs(rw)
/dev/sda1on/boottypeext4(rw)
/dev/sda3on/datatypeext4(rw)
none on /proc/sys/fs/binfmt_misctypebinfmt_misc(rw)
/dev/mapper/myvg-mydataon/mydatatypeext4(rw)

为了便于管理在/mydata目录下再创建个子目录data用于存放数据

[[email protected] ~]# mkdir /mydata/data
[[email protected] ~]# ls /mydata/
data  lost+found

新建用户以安全方式运行进程

[[email protected] ~]# groupadd -r mysql –g 3306
[[email protected] ~]# useradd -g 3306 –u 3306 -r -s /sbin/nologin -M -d /mydata/data mysql
[[email protected] ~]# chown -R mysql:mysql /mydata/data

安装并初始化mysql5.6.13

说明:mysql 安装包有三种式,rpm,源码包,二进制包(已编译好,解压后简单配置一下就可以用),我这里用的就是二进制包

[[email protected] src]# tar -xf mysql-5.6.12-linux-glibc2.5-x86_64.tar.gz -C /usr/local/ #-C指定解压目录
[[email protected] local]# ln -sv mysql-5.6.12-linux-glibc2.5-x86_64/ mysql #创建软链接
`mysql' -> `mysql-5.6.12-linux-glibc2.5-x86_64/'
[[email protected] local]# cd mysql
[[email protected] mysql]# ls
bin      data  include         lib  mysql-testscripts  sql-bench
COPYING  docs  INSTALL-BINARY  manREADME      share    support-files
[[email protected] mysql]#
[[email protected] mysql]# chown -R mysql:mysql . #更改属主属组
[[email protected] mysql]# ll
total 76
drwxr-xr-x  2 mysql mysql  4096 Jun 29 21:12 bin
-rw-r--r--  1 mysql mysql 17987 May 21 23:18 COPYING
drwxr-xr-x  3 mysql mysql  4096 Jun 29 21:12 data
drwxr-xr-x  2 mysql mysql  4096 Jun 29 21:12 docs
drwxr-xr-x  3 mysql mysql  4096 Jun 29 21:12 include
-rw-r--r--  1 mysql mysql  7469 May 21 23:18 INSTALL-BINARY
drwxr-xr-x  3 mysql mysql  4096 Jun 29 21:12 lib
drwxr-xr-x  4 mysql mysql  4096 Jun 29 21:12 man
drwxr-xr-x 10 mysql mysql  4096 Jun 29 21:12 mysql-test
-rw-r--r--  1 mysql mysql  2496 May 21 23:18 README
drwxr-xr-x  2 mysql mysql  4096 Jun 29 21:12 scripts
drwxr-xr-x 28 mysql mysql  4096 Jun 29 21:12 share
drwxr-xr-x  4 mysql mysql  4096 Jun 29 21:12 sql-bench
drwxr-xr-x  3 mysql mysql  4096 Jun 29 21:12 support-files

执行mysql 初始化的data存放位置的准备

[[email protected] mysql]# scripts/mysql_install_db --user=mysql --datadir=/mydata/data #执行mysql 初始化的data存放位置的准备
Installing MySQL system tables..../bin/mysqld: error whileloading shared libraries: libaio.so.1: cannot openshared object file: No such fileor directory

#初始化时报错说缺少libaio.so我们安装一下

[[email protected] mysql]# yum install libaio
[[email protected] mysql]# scripts/mysql_install_db --user=mysql --datadir=/mydata/data #再次执行mysql 初始化的data存放位置的准备
To start mysqld at boot timeyou have to copy
support-files/mysql.server to the right place foryour system
PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To doso, start the server, thenissue the following commands:
./bin/mysqladmin-uroot password 'new-password'
./bin/mysqladmin-uroot -h web.test.com password 'new-password'
Alternatively you can run:
./bin/mysql_secure_installation
whichwill also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended forproduction servers.
See the manual formoreinstructions.
You can start the MySQL daemon with:
cd. ; ./bin/mysqld_safe&
You can testthe MySQL daemon with mysql-test-run.pl
cdmysql-test; perl mysql-test-run.pl
Please report any problems with the ./bin/mysqlbugscript!
The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licensesathttp://shop.mysql.com
WARNING: Found existing config file./my.cnf on the system.
Because this filemight be inuse, it was not replaced,
but was used inbootstrap (unless you used --defaults-file)
and when you later start the server.
The new default config filewas created as ./my-new.cnf,
please compare it with your fileand take the changes you need.
WARNING: Default config file/etc/my.cnf exists on the system
This filewill be readby default by the MySQL server
If you donot want to use this, either remove it, or use the
--defaults-fileargument to mysqld_safe when starting the server
[[email protected] mysql]#
[[email protected] mysql]# ls /mydata/data/ #查看 data 目录有文件说明初始化成功
ibdata1  ib_logfile0  ib_logfile1  mysql  performance_schema  test

初始化完成后mysql中目录文件的属主应改回成root,以免被别人攻破mysql用户密码而带来数据破坏等

[[email protected] mysql]# cd /usr/local/mysql/
[[email protected] mysql]# chown root /usr/local/mysql/* -R
[[email protected] mysql]# ll
total 84
drwxr-xr-x  2 root mysql  4096 Jun 29 21:12 bin
-rw-r--r--  1 root mysql 17987 May 21 23:18 COPYING
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 data
drwxr-xr-x  2 root mysql  4096 Jun 29 21:12 docs
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 include
-rw-r--r--  1 root mysql  7469 May 21 23:18 INSTALL-BINARY
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 lib
drwxr-xr-x  4 root mysql  4096 Jun 29 21:12 man
-rw-r--r--  1 root root    943 Jun 29 21:18 my.cnf
-rw-r--r--  1 root root    943 Jun 29 21:23 my-new.cnf
drwxr-xr-x 10 root mysql  4096 Jun 29 21:12 mysql-test
-rw-r--r--  1 root mysql  2496 May 21 23:18 README
drwxr-xr-x  2 root mysql  4096 Jun 29 21:12 scripts
drwxr-xr-x 28 root mysql  4096 Jun 29 21:12 share
drwxr-xr-x  4 root mysql  4096 Jun 29 21:12 sql-bench
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 support-files

为mysql提供主配置文件

注,初始化后会自动在当前目录下创建一个my.cnf配置文件,直接修改就可以(在mysql 5.6 以后配置文件自动生成,不需要我们再进行复制)

查看配置文件

[[email protected] mysql]# ll
total 84
drwxr-xr-x  2 root mysql  4096 Jun 29 21:12 bin
-rw-r--r--  1 root mysql 17987 May 21 23:18 COPYING
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 data
drwxr-xr-x  2 root mysql  4096 Jun 29 21:12 docs
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 include
-rw-r--r--  1 root mysql  7469 May 21 23:18 INSTALL-BINARY
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 lib
drwxr-xr-x  4 root mysql  4096 Jun 29 21:12 man
-rw-r--r--  1 root root    943 Jun 29 21:18 my.cnf
-rw-r--r--  1 root root    943 Jun 29 21:23 my-new.cnf
drwxr-xr-x 10 root mysql  4096 Jun 29 21:12 mysql-test
-rw-r--r--  1 root mysql  2496 May 21 23:18 README
drwxr-xr-x  2 root mysql  4096 Jun 29 21:12 scripts
drwxr-xr-x 28 root mysql  4096 Jun 29 21:12 share
drwxr-xr-x  4 root mysql  4096 Jun 29 21:12 sql-bench
drwxr-xr-x  3 root mysql  4096 Jun 29 21:12 support-files
[[email protected] mysql]#
[[email protected] mysql]# cat my.cnf
# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html
[mysqld]
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
# These are commonly set, remove the # and set as required.
# basedir = .....
# datadir = .....
# port = .....
# server_id = .....
# socket = .....
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
[[email protected] mysql]#

注,大家可以看到生成的配置文件很简单,我们得添加一些内容!

修改配置文件

[[email protected] mysql]# vim my.cnf
添加内容是:
binlog-format=ROW
log-bin=master-bin.log
log-slave-updates=true
gtid-mode=on
enforce-gtid-consistency=true
master-info-repository=TABLE
relay-log-info-repository=TABLE
sync-master-info=1
slave-parallel-workers=2
binlog-checksum=CRC32
master-verify-checksum=1
slave-sql-verify-checksum=1
binlog-rows-query-log_events=1
server-id=1
report-port=3306
port=3306
datadir=/mydata/data
socket=/tmp/mysql.sock
report-host=master.test.com

为mysql提供sysv服务脚本并启动服务

[[email protected] mysql]# cp support-files/mysql.server /etc/init.d/mysqld #复制sysv脚本
[[email protected] mysql]# chkconfig --add mysqld
[[email protected] mysql]# chkconfig mysqld on #开机自启动
[[email protected] mysql]# chkconfig mysqld --list
mysqld          0:off   1:off   2:on    3:on    4:on    5:on    6:off
[[email protected] mysql]# service mysqld start
Starting MySQL.... SUCCESS!
[[email protected] mysql]# netstat -ntulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Programname
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      990/sshd
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1066/master
tcp        0      0 :::80                       :::*                        LISTEN      37120/httpd
tcp        0      0 :::22                       :::*                        LISTEN      990/sshd
tcp        0      0 ::1:25                      :::*                        LISTEN      1066/master
tcp        0      0 :::3306                     :::*                        LISTEN      37924/mysqld#mysql启动成功
udp        0      0 0.0.0.0:68                  0.0.0.0:*                               890/dhclient

输出mysql的man手册至man命令的查找路径

[[email protected] mysql]# vim /etc/man.config
MANPATH /usr/local/mysql/man#增加这一行

输出mysql的头文件至系统头文件路径/usr/include

[[email protected] mysql]# ln -sv /usr/local/mysql/include/ /usr/include/mysql #输出mysql的头文件至系统头文件
`/usr/include/mysql' -> `/usr/local/mysql/include/'
[[email protected] mysql]# cd /usr/include/mysql/

输出mysql的库文件给系统库查找路径

[[email protected] mysql]# vim /etc/ld.so.conf.d/mysql.conf
/usr/local/mysql/lib#直接新建编辑/etc/ld.so.conf.d/mysql.conf文件,把mysql的库文件路径添加进去就可以了
~       
[[email protected] mysql]# ldconfig –v# 让系统重新读取库文件
/usr/local/mysql/lib:
libtcmalloc_minimal.so.0 -> libtcmalloc_minimal.so (changed)
libmysqlclient.so.18 -> libmysqlclient_r.so.18.0.0
/usr/lib64/mysql:
libmysqlclient.so.16 -> libmysqlclient.so.16.0.0
libmysqlclient_r.so.16 -> libmysqlclient_r.so.16.0

修改PATH环境变量,让系统可以直接使用mysql的相关命令

[[email protected] mysql]# vim /etc/profile.d/mysql.sh  #添加环境变量(与添加httpd是一样的)
exportPATH=$PATH:/usr/local/mysql/bin
[[email protected] mysql]# source /etc/profile #重新读取一下环境变量

测试并连接mysql

[[email protected] mysql]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection idis 1
Server version: 5.6.12-log MySQL Community Server (GPL)
Copyright (c) 2000, 2013, Oracle and/oritsaffiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/orits
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;'or '\h'forhelp. Type '\c'to clearthe current input statement.
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test|
+--------------------+
4 rows inset(0.02 sec)
mysql>

(3).安装并配置php

解决依赖关系

[[email protected] ~]# yum -y groupinstall "Development Tools"

如果想让编译的php支持mcrypt、mhash扩展和libevent得用yum安装一下

[[email protected] ~]# yum -y install libmcrypt
[[email protected] ~]# yum -y install libmcrypt-devel
[[email protected] ~]# yum -y install mhash
[[email protected] ~]# yum -y install mhash-devel
[[email protected] ~]# yum -y install mcrypt

另外,也可以根据需要安装libevent,系统一般会自带libevent,但版本有些低。

[[email protected] ~]# yum -y install libevent
[[email protected] ~]# yum -y install libevent-devel

说明:libevent是一个异步事件通知库文件,其API提供了在某文件描述上发生某事件时或其超时时执行回调函数的机制,它主要用来替换事件驱动的网络服务器上的event loop机制。目前来说, libevent支持/dev/poll、kqueue、select、poll、epoll及Solaris的event ports。

若要支持更多的图片格式与字体可以安装以下软件

[[email protected] ~]# yum -y install gd gd-devel  libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel

安装libxml(扩展标记语言)库

[[email protected] ~]# yum -y  install libxml2 libxml2-devel

安装bzip2压缩库

[[email protected] ~]# yum install -y bzip2 bzip2-devel

安装libcurl传输库

[[email protected] ~]# yum install -y libcurl libcurl-devel

配置php

[[email protected] php-5.4.19]# ./configure --prefix=/usr/local/php --with-mysql=/usr/local/mysql --with-openssl --enable-fpm --enable-sockets --enable-sysvshm  --with-mysqli=/usr/local/mysql/bin/mysql_config --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib-dir --with-libxml-dir=/usr/ --enable-xml  --with-mhash --with-mcrypt  --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2 --with-curl

当看到以下代码,说明配置成功:

Generating files
configure: creating ./config.status
creating main/internal_functions.c
creating main/internal_functions_cli.c
+--------------------------------------------------------------------+
| License:                                                           |
| This software is subject to the PHP License, available in this     |
| distribution in the file LICENSE.  By continuing this installation |
| process, you are bound by the terms of this license agreement.     |
| If you do not agree with the terms of this license, you must abort |
| the installation process at this point.                            |
+--------------------------------------------------------------------+
Thank you for using PHP.
config.status: creating php5.spec
config.status: creating main/build-defs.h
config.status: creating scripts/phpize
config.status: creating scripts/man1/phpize.1
config.status: creating scripts/php-config
config.status: creating scripts/man1/php-config.1
config.status: creating sapi/cli/php.1
config.status: creating sapi/fpm/php-fpm.conf
config.status: creating sapi/fpm/init.d.php-fpm
config.status: creating sapi/fpm/php-fpm.service
config.status: creating sapi/fpm/php-fpm.8
config.status: creating sapi/fpm/status.html
config.status: creating sapi/cgi/php-cgi.1
config.status: creating ext/phar/phar.1
config.status: creating ext/phar/phar.phar.1
config.status: creating main/php_config.h
config.status: executing default commands

编译安装PHP

[[email protected] php-5.4.19]# make && make install

为php提供配置文件

[[email protected] php-5.4.19]# cp php.ini-production /etc/php.ini

为php-fpm提供Sysv init脚本,并将其添加至服务列表

[[email protected] php-5.4.19]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[[email protected] php-5.4.19]# chmod +x /etc/init.d/php-fpm
[[email protected] php-5.4.19]# chkconfig --add php-fpm
[[email protected] php-5.4.19]# chkconfig php-fpm on

为php-fpm提供配置文件

[[email protected] ~]# cd /usr/local/php/
[[email protected] php]# ls
bin  etc  include  lib  php  sbin  var
[[email protected] php]# cd etc/
[[email protected] etc]# ls
pear.conf  php-fpm.conf.default
[[email protected] etc]# cp php-fpm.conf.default php-fpm.conf

修改php-fpm的配置文件

注,配置fpm的相关选项为你所需要的值,并启用pid文件(如下最后一行)

pm.max_children = 150
pm.start_servers = 8
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pid = /usr/local/php/var/run/php-fpm.pid

启动php-fpm

[[email protected] etc]# service php-fpm start
Starting php-fpm  done

查看一下

[[email protected] etc]# ps aux | grep php-fpm
root     12511  0.0  2.1 186620  5144 ?        Ss   10:52   0:00 php-fpm: master process (/usr/local/php/etc/php-fpm.conf)                                                               
nobody   12512  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www                                                                                                       
nobody   12513  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www                                                                                                       
nobody   12514  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www                                                                                                       
nobody   12515  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www                                                                                                       
nobody   12516  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www                                                                                                       
nobody   12517  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www                                                                                                       
nobody   12518  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www                                                                                                       
nobody   12519  0.0  1.8 186620  4284 ?        S    10:52   0:00 php-fpm: pool www

好了,到这里PHP这安装配置完成了,下面我们来整合Nginx与PHP。

(4).nginx整合php

修改nginx配置文件,启用如下选项。

location ~ \.php$ {   
        root           /data/www;    
        fastcgi_pass   127.0.0.1:9000;    
        fastcgi_index  index.php;    
        fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;    
        include        fastcgi_params;    
    }

编辑/etc/nginx/fastcgi_params,将其内容更改为如下内容:  

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;    
fastcgi_param  SERVER_SOFTWARE    nginx;    
fastcgi_param  QUERY_STRING       $query_string;    
fastcgi_param  REQUEST_METHOD     $request_method;    
fastcgi_param  CONTENT_TYPE       $content_type;    
fastcgi_param  CONTENT_LENGTH     $content_length;    
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;    
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;    
fastcgi_param  REQUEST_URI        $request_uri;    
fastcgi_param  DOCUMENT_URI       $document_uri;    
fastcgi_param  DOCUMENT_ROOT      $document_root;    
fastcgi_param  SERVER_PROTOCOL    $server_protocol;    
fastcgi_param  REMOTE_ADDR        $remote_addr;    
fastcgi_param  REMOTE_PORT        $remote_port;    
fastcgi_param  SERVER_ADDR        $server_addr;    
fastcgi_param  SERVER_PORT        $server_port;    
fastcgi_param  SERVER_NAME        $server_name;

并在所支持的主页面格式中添加php格式的主页    
类似如下:  

location / {    
         root   /data/www;    
         index  index.php index.html index.htm;    
    }

重新加载一下nginx的配置文件    

[[email protected] ~]# service nginx reload    
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok    
nginx: configuration file /etc/nginx/nginx.conf test is successful    
重新载入 nginx:                                           [确定]

新建index.php的测试页面,测试php是否能正常工作

[[email protected] ~]# cd /data/www/   
[[email protected] www]# vim index.php    
<?php    
    phpinfo();    
?>

接着就可以通过浏览器访问此测试页面了,效果如下。

Memcache 应用详解

(5).安装并配置xcache

安装xcache

[[email protected] ~]# cd src/   
[[email protected] src]# tar xf xcache-3.0.3.tar.gz    
[[email protected] src]# cd xcache-3.0.3    
[[email protected] xcache-3.0.3]# /usr/local/php/bin/phpize    
Configuring for:    
PHP Api Version:         20100412    
Zend Module Api No:      20100525    
Zend Extension Api No:   220100525    
[[email protected] xcache-3.0.3]# ./configure --enable-xcache --with-php-config=/usr/local/php/bin/php-config
[[email protected] xcache-3.0.3]# make && make install

安装结束时,会出现类似如下行

Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/

编辑php.ini,整合php和xcache,首先将xcache提供的样例配置导入php.ini

[[email protected] xcache-3.0.3]# mkdir /etc/php.d
[[email protected] xcache-3.0.3]# cp xcache.ini /etc/php.d/   
[[email protected] xcache-3.0.3]# ls /etc/php.d/    
xcache.in

说明:xcache.ini文件在xcache的源码目录中。

接下来编辑/etc/php.d/xcache.ini,找到zend_extension开头的行,修改为如下行

[[email protected] ~]# vim /etc/php.d/xcache.ini
extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/xcache.so

注意:如果php.ini文件中有多条zend_extension指令行,要确保此新增的行排在第一位。

重新启动php-fpm  

[[email protected] ~]# service php-fpm restart   
Gracefully shutting down php-fpm . done    
Starting php-fpm  done

查看一下是否配置成功

Memcache 应用详解

注,这是没有配置xcache之前截图。

Memcache 应用详解

注,这是配置xcache之后的截图。好了,到这里我们的lnmp环境配置完成。

三、memcache 应用一 php与memcache

1.实验拓扑

Memcache 应用详解

2.PHP的memcache的客户端

PHP有两个memcache客户端:php memcache和php memcached。php memcache独立用php实现,是老客户端,从我们实践中已发现有多个问题,而且功能少,属性也可设置的少;php memcached是基于原生的c的libmemcached的扩展,更加完善,建议替换为php memcached。

3.PHP memcache的问题

(1).分布式问题

php memcache默认会自动切换实例,所以有时取到老数据,并且value飘忽不定

(2).高并发下稳定性问题

php memcache换成php memcached,在高并发下稳定下极大提高;

(3).秒超时间隔没法修改问题

php memcache客户端有个1秒超时间隔没法修改问题:bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )第三个参数本来可设置timeout,单位秒,但无法修改。

测试了以下三种修改timeout的方法都无效:

  • 用memcache api Memcache::setServerParams不能修改;

  • 改memcache 源代码vi php_memcache.h宏定义不能修改;

  • php.ini内这个配置:default_socket_timeout = 60对本timeout无效。

(4).memcache和memcached对比

注,PHP memcache这个老客户端在属性设置方面可设置的很少,出错码粒度很粗,出错后难以定位,而且功能欠缺一些,如下图:

Memcache 应用详解

注,综合上述建议大家使用php memcached。还有更多知识点请参考官方文档:https://code.google.com/p/memcached/wiki/PHPClientComparison

4.PHP 安装memcached扩展

[[email protected] src]# tar xf memcached-2.0.1.tgz   
[[email protected] src]# cd memcached-2.0.1    
[[email protected] memcached-2.0.1]# ls    
ChangeLog   CREDITS  g_fmt.h            memcached.ini              php_memcached.h          README.markdown    
config.m4   fastlz   LICENSE            php_libmemcached_compat.h  php_memcached_session.c    
config.w32  g_fmt.c  memcached-api.php  php_memcached.c            php_memcached_session.h    
[[email protected] memcached-2.0.1]# /usr/local/php/bin/phpize    
Configuring for:    
PHP Api Version:         20100412    
Zend Module Api No:      20100525    
Zend Extension Api No:   220100525    
[[email protected] memcached-2.0.1]# ./configure  --with-php-config=/usr/local/php/bin/php-config

出错:

checking for libmemcached location... configure: error: memcached support requires libmemcached 1.0.x. Use --with-libmemcached-dir=<DIR> to specify the prefix where libmemcached headers and library are located

方案:安装libmemcached

[[email protected] src]# tar xf libmemcached-1.0.12.tar.gz   
[[email protected] src]# cd libmemcached-1.0.12    
[[email protected] libmemcached-1.0.12]# ./configure
[[email protected] libmemcached-1.0.12]# make && make install

继续编译memcached-2.1.0

[[email protected] memcached-2.1.0]# ./configure  --with-php-config=/usr/local/php/bin/php-config
[[email protected] memcached-2.1.0]# make   
/bin/sh /root/src/memcached-2.1.0/libtool --mode=compile cc -I/usr/local/php/include/php  -I. -I/root/src/memcached-2.1.0 -DPHP_ATOM_INC -I/root/src/memcached-2.1.0/include -I/root/src/memcached-2.1.0/main -I/root/src/memcached-2.1.0 -I/usr/local/php/include/php -I/usr/local/php/include/php/main -I/usr/local/php/include/php/TSRM -I/usr/local/php/include/php/Zend -I/usr/local/php/include/php/ext -I/usr/local/php/include/php/ext/date/lib  -DHAVE_CONFIG_H  -g -O2   -c /root/src/memcached-2.1.0/php_memcached.c -o php_memcached.lo    
mkdir .libs    
cc -I/usr/local/php/include/php -I. -I/root/src/memcached-2.1.0 -DPHP_ATOM_INC -I/root/src/memcached-2.1.0/include -I/root/src/memcached-2.1.0/main -I/root/src/memcached-2.1.0 -I/usr/local/php/include/php -I/usr/local/php/include/php/main -I/usr/local/php/include/php/TSRM -I/usr/local/php/include/php/Zend -I/usr/local/php/include/php/ext -I/usr/local/php/include/php/ext/date/lib -DHAVE_CONFIG_H -g -O2 -c /root/src/memcached-2.1.0/php_memcached.c  -fPIC -DPIC -o .libs/php_memcached.o    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘php_memc_get_impl’中:    
/root/src/memcached-2.1.0/php_memcached.c:599: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘php_memc_getMulti_impl’中:    
/root/src/memcached-2.1.0/php_memcached.c:797: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c:800: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘zim_Memcached_fetch’中:    
/root/src/memcached-2.1.0/php_memcached.c:1014: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c:1017: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘zim_Memcached_fetchAll’中:    
/root/src/memcached-2.1.0/php_memcached.c:1068: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c:1071: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c:1121:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘zim_Memcached_getServerByKey’中:    
/root/src/memcached-2.1.0/php_memcached.c:1977: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c:2178:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c:2235:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c:2246:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c:2275:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘php_memc_set_option’中:    
/root/src/memcached-2.1.0/php_memcached.c:2280: 错误:‘memcached_st’没有名为‘hash’的成员    
/root/src/memcached-2.1.0/php_memcached.c:2321:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘php_memc_do_serverlist_callback’中:    
/root/src/memcached-2.1.0/php_memcached.c:2583: 警告:传递‘add_assoc_string_ex’的第 4 个实参时丢弃了指针目标类型的限定    
/usr/local/php/include/php/Zend/zend_API.h:379: 附注:需要类型‘char *’,但实参的类型为‘const char *’    
/root/src/memcached-2.1.0/php_memcached.c:2677:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘php_memc_handle_error’中:    
/root/src/memcached-2.1.0/php_memcached.c:2680: 错误:‘memcached_st’没有名为‘cached_errno’的成员    
/root/src/memcached-2.1.0/php_memcached.c:2688:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c:2691: 错误:‘memcached_st’没有名为‘cached_errno’的成员    
/root/src/memcached-2.1.0/php_memcached.c: 在函数‘php_memc_do_result_callback’中:    
/root/src/memcached-2.1.0/php_memcached.c:3191: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c:3194: 警告:赋值丢弃了指针目标类型的限定    
/root/src/memcached-2.1.0/php_memcached.c:3522:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c:3680:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c:3705:42: 错误:标识符“@”在预处理表达式中无效    
/root/src/memcached-2.1.0/php_memcached.c:3709:42: 错误:标识符“@”在预处理表达式中无效    
make: *** [php_memcached.lo] 错误 1

注,make一直报错,检查好长时间不发现,问题最后用PECL安装,还是会报同样的错误,可能是因为php版本太高了,朋友测试可以用低一点的版本试一下,嘿嘿。好了,本来想把php两个memcache扩展都安装上的,现在php memcached扩展报错,所以我们这里只安装php memcache扩展,下面我们来演示一下怎么用PECL来安装php扩展。

5.PECL 简介

       PECL 的全称是 The PHP Extension Community Library ,是一个开放的并通过 PEAR(PHP Extension and Application Repository,PHP 扩展和应用仓库)打包格式来打包安装的 PHP 扩展库仓库。通过 PEAR 的 Package Manager 的安装管理方式,可以对 PECL 模块进行下载和安装。与以往的多数 PEAR 包不同的是,PECL 扩展包含的是可以编译进 PHP Core 的 C 语言代码,因此可以将 PECL 扩展库编译成为可动态加载的 .so 共享库,或者采用静态编译方式与 PHP 源代码编译为一体的方法进行扩展。PECL 扩展库包含了对于 XML 解析,数据库访问,邮件解析,嵌入式的 Perl 以及 Pthyon 脚本解释器等诸多的 PHP 扩展模块,因此从某种意义上来说,在运行效率上 PECL 要高于以往诸多的 PEAR 扩展库。

6.PECL 使用

[[email protected] ~]# /usr/local/php/bin/pecl -h   
Commands:    
build                  Build an Extension From C Source    
bundle                 Unpacks a Pecl Package    
channel-add            Add a Channel    
channel-alias          Specify an alias to a channel name    
channel-delete         Remove a Channel From the List    
channel-discover       Initialize a Channel from its server    
channel-info           Retrieve Information on a Channel    
channel-login          Connects and authenticates to remote channel server    
channel-logout         Logs out from the remote channel server    
channel-update         Update an Existing Channel    
clear-cache            Clear Web Services Cache    
config-create          Create a Default configuration file    
config-get             Show One Setting    
config-help            Show Information About Setting    
config-set             Change Setting    
config-show            Show All Settings    
convert                Convert a package.xml 1.0 to package.xml 2.0 format    
cvsdiff                Run a "cvs diff" for all files in a package    
cvstag                 Set CVS Release Tag    
download               Download Package    
download-all           Downloads each available package from the default channel    
info                   Display information about a package    
install                Install Package    
list                   List Installed Packages In The Default Channel    
list-all               List All Packages    
list-channels          List Available Channels    
list-files             List Files In Installed Package    
list-upgrades          List Available Upgrades    
login                  Connects and authenticates to remote server [Deprecated in favor of channel-login]    
logout                 Logs out from the remote server [Deprecated in favor of channel-logout]    
makerpm                Builds an RPM spec file from a PEAR package    
package                Build Package    
package-dependencies   Show package dependencies    
package-validate       Validate Package Consistency    
pickle                 Build PECL Package    
remote-info            Information About Remote Packages    
remote-list            List Remote Packages    
run-scripts            Run Post-Install Scripts bundled with a package    
run-tests              Run Regression Tests    
search                 Search remote package database    
shell-test             Shell Script Test    
sign                   Sign a package distribution file    
svntag                 Set SVN Release Tag    
uninstall              Un-install Package    
update-channels        Update the Channel List    
upgrade                Upgrade Package    
upgrade-all            Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]    
Usage: pecl [options] command [command-options] <parameters>    
Type "pecl help options" to list all options.    
Type "pecl help shortcuts" to list all command shortcuts.    
Type "pecl help <command>" to get the help for the specified command.

7.常用命令

  • search 查找一下模块

  • info 查看模块信息

  • install 安装查找到的模块

注,下面我们来演示一下,怎么安装php memcache模块。

[[email protected] ~]#  /usr/local/php/bin/pecl install memcache

说明:看到下面的信息,就说明php memcache 模块安装完成。

Build process completed successfully   
Installing '/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/memcache.so'    
install ok: channel://pecl.php.net/memcache-2.2.7    
configuration option "php_ini" is not set to php.ini location    
You should add "extension=memcache.so" to php.ini

接下来我们来增加php memcache的配置文件,

[[email protected] ~]# cd /etc/php.d/   
[[email protected] php.d]# vim memcache.ini
extension = "memcache.so"   
memcache.chunk_size = 32768

重启一下php-fpm

[[email protected] ~]# service php-fpm restart   
Gracefully shutting down php-fpm . done    
Starting php-fpm  done

下面我们来查看一下php的模块

[[email protected] ~]# /usr/local/php/bin/php -m   
[PHP Modules]    
bz2    
Core    
ctype    
curl    
date    
dom    
ereg    
fileinfo    
filter    
hash    
iconv    
json    
libxml    
mbstring    
mcrypt    
memcache #php memcache模块已安装    
mhash    
mysql    
mysqli    
openssl    
pcre    
PDO    
pdo_sqlite    
Phar    
posix    
Reflection    
session    
SimpleXML    
sockets    
SPL    
sqlite3    
standard    
sysvshm    
tokenizer    
XCache    
XCache Cacher    
xml    
xmlreader    
xmlwriter    
zlib
[Zend Modules]   
XCache    
XCache Cacher

注,php 的memcach模块安装完成,我们也可以用phpinfo()信息来查看一下。如下图,

Memcache 应用详解

好了,既然说到了php的模块安装,下面我们就说一下php模块的安装方法,对于初学都应该很帮助哦。

8.php扩展模快速自动安装

说明:php开发简单,速度快,以及扩展灵活,在最近一些年,越来越得到广泛应用。 以前说到安装php模块,走过很多弯路。听人说可以用,rpm包,也可以用源码安装。 这些对于linux 初学者有时候真是一头雾水。 其实,安装扩展模块并没有想象那么复杂,而且只要我们用php自带的模块安装命令就可以很好的完成。下面我们来说一说,下载、编译、安装一步到位的方法。

(1).下载模块

[[email protected] bin]# wget http://pear.php.net/go-pear.phar

(2).安装模块

[[email protected] ~]# /usr/local/php/bin/php go-pear.phar
Below is a suggested file layout for your new PEAR installation.  To   
change individual locations, type the number in front of the    
directory.  Type 'all' to change all of them or simply press Enter to    
accept these locations.
1. Installation base ($prefix)                   : /usr/local/php   
2. Temporary directory for processing            : /tmp/pear/install    
3. Temporary directory for downloads             : /tmp/pear/install    
4. Binaries directory                            : /usr/local/php/bin    
5. PHP code directory ($php_dir)                 : /usr/local/php/lib/php    
6. Documentation directory                       : /usr/local/php/docs    
7. Data directory                                : /usr/local/php/data    
8. User-modifiable configuration files directory : /usr/local/php/cfg    
9. Public Web Files directory                    : /usr/local/php/www    
10. Tests directory                               : /usr/local/php/tests    
11. Name of configuration file                    : /usr/local/php/etc/pear.conf
[[email protected] ~]# cd /usr/local/php/bin/   
[[email protected] bin]# ls    
pear  peardev  pecl  phar  phar.phar  php  php-cgi  php-config  phpize

注,可以选择:1 设置你安装路径,但我们这里默认就行,接下来,一路回车就可以完成安装了。这里安装方法之一,我认为是比较方便的,下面我们来说说,用pecl或pear这2个命令进行安装。上面我已经简单和大家说了一下,pecl的用法,下面我们来继续说一说。

(3).什么是pear、pecl 呢?

       Pear、Pecl都是PHP扩展模块的集合。扩展PHP有两种方法:一种是用纯粹的PHP代码写函数和类。Pear就是这样一个项目。PEAR是PHP的官方开源类库(PHP Extension and Application Repository的缩写)。Pear在英文中是梨子的意思。PEAR将PHP程序开发过程中常用的功能编写成类库,涵盖了页面呈面、数据库访问、文件操作、数据结构、缓存操作、网络协议等许多方面,用户可以很方便地使用。它是一个PHP扩展及应用的一个代码仓库,简单地说,PEAR就是PHP的cpan。其主页是pear.php.net。

   另外一种是用c或者c++编写外部模块加载至php中。Pecl(The PHP Extension Community Library)就是干这个事的,PHP的标准扩展,可以补充实际开发中所需的功能。所有的扩展都需要安装,在Windows下面以DLL的形式出现;在 linux下面需要单独进行编译,它的表现形式为根据PHP官方的标准用C语言写成,尽管源码开放但是一般人无法随意更改源码。其主页是 pecl.php.net。最直接的表述:Pear是PHP的上层扩展,Pecl是PHP的底层扩展。这两种方法其实都是为特定的应用提供现成的函数或者类,本质上来说都是一样的。知道上面2个区别,对于我们安装就很方便理解了。我们一般用*.so文件扩展,需要运行:pecl。一般常用的还是使用pecl扩展。

(4).pecl使用

[[email protected] ~]# /usr/local/php/bin/pecl search memcache   
Retrieving data...0%    
..Matched packages, channel pecl.php.net:    
=======================================    
Package          Stable/(Latest) Local    
memcache         3.0.8 (beta)    2.2.7 memcached extension    
memcached        2.1.0 (stable)        PHP extension for interfacing with memcached via libmemcached library    
mysqlnd_memcache 1.0.1 (stable)        A PHP extension for transparently translating SQL into requests for the MySQL InnoDB Memcached Daemon Plugin

先运行:search 命令模糊搜索,然后可以用,pecl install memcache。一路回车即可。然后查看一下安装的模块,

[[email protected] ~]# cd /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/   
[[email protected] no-debug-non-zts-20100525]# ls    
memcache.so  xcache.so

注,(不同系统,位置可能不同),上一步安装完后,会告诉模块所在地址。接下来修改一下配置文件并重启php-fpm。然后,可以通过php -m查看下。与上面步骤相同这里就不在演示。好了,php memcache的模块已安装完成,下面我们来安装一下memcache服务器。

9.安装memcache服务器

(1).安装libevent

注,在上文中提到memcached是基于libevent进行事件处理的,所以我们得先安装libevent。

[[email protected] src]# tar xf libevent-2.0.21-stable.tar.gz
[[email protected] src]# cd libevent-2.0.21-stable
[[email protected] libevent-2.0.21-stable]# ./configure --prefix=/usr/local/libevent
[[email protected] libevent-2.0.21-stable]# make && make install

(2).安装memcached

[[email protected] src]# tar xf memcached-1.4.15.tar.gz
[[email protected] src]# cd memcached-1.4.15
[[email protected] memcached-1.4.15]# ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local/libevent
[[email protected] memcached-1.4.15]# make && make install

(3).配置环境变量

[[email protected] ~]# vim /etc/profile.d/memcache.sh
[[email protected] ~]# cat /etc/profile.d/memcache.sh 
exportPATH=$PATH:/usr/local/memcached/bin/
[[email protected] ~]# source /etc/profile 
[[email protected] ~]# memcached -h 
memcached 1.4.15 
-p <num>      TCP port number to listen on (default: 11211) 
-U <num>      UDP port number to listen on (default: 11211, 0 is off) 
-s <file>     UNIX socket path to listen on (disables network support) 
-a <mask>     access mask forUNIX socket, inoctal (default: 0700) 
-l <addr>     interface to listen on (default: INADDR_ANY, all addresses) 
<addr> may be specified as host:port. If you don't specify 
a port number, the value you specified with -p or -U is 
used. You may specify multiple addresses separated by comma 
or by using -l multiple times
-d            run as a daemon 
-r            maximize core filelimit 
-u <username> assume identity of <username> (only when run as root) 
-m <num>      max memory to use foritems inmegabytes (default: 64 MB) 
-M            returnerror on memory exhausted (rather than removing items) 
-c <num>      max simultaneous connections (default: 1024) 
-k            lock down all paged memory.  Note that there is a 
limit on how much memory you may lock.  Trying to 
allocate morethan that would fail, so be sure you 
setthe limit correctly forthe user you started 
the daemon with (not for-u <username> user; 
under sh this is donewith 'ulimit -S -l NUM_KB'). 
-vverbose (print errors/warningswhileinevent loop) 
-vv           very verbose (also print client commands/reponses) 
-vvv          extremely verbose (also print internal state transitions) 
-h            print this help and exit
-i            print memcached and libevent license 
-P <file>     save PID in<file>, only used with -d option 
-f <factor>   chunk size growth factor (default: 1.25) 
-n <bytes>    minimum space allocated forkey+value+flags (default: 48) 
-L            Try to use large memory pages (ifavailable). Increasing 
the memory page size could reduce the number of TLB misses 
and improve the performance. In order to get large pages 
from the OS, memcached will allocate the total item-cache 
inone large chunk. 
-D <char>     Use <char> as the delimiter between key prefixes and IDs. 
This is used forper-prefix stats reporting. The default is 
":"(colon). If this option is specified, stats collection 
is turned on automatically; ifnot, thenit may be turned on 
by sending the "stats detail on"commandto the server. 
-t <num>      number of threads to use (default: 4) 
-R            Maximum number of requests per event, limits the number of 
requests process fora given connection to prevent 
starvation (default: 20) 
-C            Disable use of CAS 
-b            Set the backlog queue limit (default: 1024) 
-B            Binding protocol - one of ascii, binary, or auto (default) 
-I            Override the size of each slab page. Adjusts max item size 
(default: 1mb, min: 1k, max: 128m) 
-o            Comma separated list of extended or experimental options 
- (EXPERIMENTAL) maxconns_fast: immediately close new 
connections ifover maxconns limit 
- hashpower: An integer multiplier forhow large the hash
table should be. Can be grown at runtime ifnot big enough. 
Set this based on "STAT hash_power_level"before a 
restart.

(4).memcached 启动选项

[[email protected] ~]# memcached -h
-p TCP监听端口 (default: 11211)
-U UDP 监听端口 (default: 11211, 0 is off)
-s UNIX socket监听路径,不支持网络
-a UNIX socket访问掩码, 八进制 (default: 0700)
-l 监听的服务器IP地址 (default: all addresses)
-d 启动一个守护进程
-r 最大限度利用核心文件限制
-u 运行memcached用户
-m 最大的内存使用 (default: 64 MB)
-M 内存耗尽返回错误
-c 最大并发连接 (default: 1024)
-k 锁定所有分页内存
-v 输出警告和错误信息
-vv 同时打印客户端请求和返回信息
-vvv 打印内部状态转换信息
-i 打印memcached 和 libevent 版本信息
-P 设置保存pid文件, only used with -d option
-f 块大小增长倍数 (default: 1.25)
-n key+value+flags最小分配空间(default: 48)
-L 如何有效,尝试使用大内存页。增加内存页大小可以减少失误的TLB数量,提高性能。
-D 指定key和IDs的分隔符 default is “:” (colon). 如果指定此选项,统计信息收集自动开启;
-t 使用的线程数量 (default: 4)
-R 每个事件的最大请求数 (default: 20)
-C 禁止使用 CAS
-b 设置积压队列数限制 (default: 1024)、
-B 绑定协议 – one of ascii, binary, or auto (default)
-I 分配给每个slab页(default: 1mb, min: 1k, max: 128m)
-o 配置额外选项

(5).启动memcached

[[email protected] ~]# memcached -d -m 500 -u root -l 192.168.18.201 -c 256 -P /tmp/memcached.pid -vvv
slab class   1: chunk size        96 perslab   10922 
slab class   2: chunk size       120 perslab    8738 
slab class   3: chunk size       152 perslab    6898 
slab class   4: chunk size       192 perslab    5461 
slab class   5: chunk size       240 perslab    4369 
slab class   6: chunk size       304 perslab    3449 
slab class   7: chunk size       384 perslab    2730 
slab class   8: chunk size       480 perslab    2184 
slab class   9: chunk size       600 perslab    1747 
slab class  10: chunk size       752 perslab    1394 
slab class  11: chunk size       944 perslab    1110 
slab class  12: chunk size      1184 perslab     885 
slab class  13: chunk size      1480 perslab     708 
slab class  14: chunk size      1856 perslab     564 
slab class  15: chunk size      2320 perslab     451 
slab class  16: chunk size      2904 perslab     361 
slab class  17: chunk size      3632 perslab     288 
slab class  18: chunk size      4544 perslab     230 
slab class  19: chunk size      5680 perslab     184 
slab class  20: chunk size      7104 perslab     147 
slab class  21: chunk size      8880 perslab     118 
slab class  22: chunk size     11104 perslab      94 
slab class  23: chunk size     13880 perslab      75 
slab class  24: chunk size     17352 perslab      60 
slab class  25: chunk size     21696 perslab      48 
slab class  26: chunk size     27120 perslab      38 
slab class  27: chunk size     33904 perslab      30 
slab class  28: chunk size     42384 perslab      24 
slab class  29: chunk size     52984 perslab      19 
slab class  30: chunk size     66232 perslab      15 
slab class  31: chunk size     82792 perslab      12 
slab class  32: chunk size    103496 perslab      10 
slab class  33: chunk size    129376 perslab       8 
slab class  34: chunk size    161720 perslab       6 
slab class  35: chunk size    202152 perslab       5 
slab class  36: chunk size    252696 perslab       4 
slab class  37: chunk size    315872 perslab       3 
slab class  38: chunk size    394840 perslab       2 
[[email protected] ~]# slab class  39: chunk size    493552 perslab       2 
slab class  40: chunk size    616944 perslab       1 
slab class  41: chunk size    771184 perslab       1 
slab class  42: chunk size   1048576 perslab       1 
<26 server listening (auto-negotiate) 
<27 send buffer was 229376, now 268435456 
<27 server listening (udp) 
<27 server listening (udp) 
<27 server listening (udp) 
<27 server listening (udp)

注,默认使用11211端口,root用户,最大使用500M内存,256个并发连接,输出详细信息,以守护进程方式运行。从输出信息可看出memcached分配内存的过程。

(6).查看一下启动端口

[[email protected] ~]# netstat -ntulp
Active Internet connections (only servers) 
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Programname
tcp        0      0 192.168.18.201:11211        0.0.0.0:*                   LISTEN      8086/memcached
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1026/sshd
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1103/master
tcp        0      0 127.0.0.1:6010              0.0.0.0:*                   LISTEN      1137/sshd
tcp        0      0 127.0.0.1:6011              0.0.0.0:*                   LISTEN      8044/sshd
tcp        0      0 :::22                       :::*                        LISTEN      1026/sshd
tcp        0      0 ::1:25                      :::*                        LISTEN      1103/master
tcp        0      0 ::1:6010                    :::*                        LISTEN      1137/sshd
tcp        0      0 ::1:6011                    :::*                        LISTEN      8044/sshd
udp        0      0 192.168.18.201:11211        0.0.0.0:*                               8086/memcached

注,大家可以看到,memcached已启动,监听在11211端口上。

(7).登录测试一下

安装telnet测试工具

[[email protected] ~]# yum install -y telnet

测试

[[email protected] ~]# telnet 192.168.18.201 11211
Trying 192.168.18.201... 
Connected to 192.168.18.201. 
Escape character is '^]'.

注,登录成功。下面我们add命令,保存一个数据。用get命令查看一下。

add 命令

用法:add keyname flag  timeout  datasize

案例:

[[email protected] ~]# telnet 192.168.18.201 11211
Trying 192.168.18.201... 
Connected to 192.168.18.201. 
Escape character is '^]'. 
add mykey 0 10 5
hello 
STORED

get 命令

用法:get keyname

案例:

get mykey
VALUE mykey 0 5 
hello 
END

注,好了测试成功。大家有没有发现,每次启动都要输入那么长的命令是不是很不方便,下面我们为memcached提供SysV的startup脚本。

(8).提供SysV的startup脚本

[[email protected] ~]# vim /etc/init.d/memcached
#!/bin/bash 
# 
# Init file for memcached 
# 
# chkconfig: - 86 14 
# description: Distributed memory caching daemon 
# 
# processname: memcached 
# config: /etc/sysconfig/memcached
. /etc/rc.d/init.d/functions
## Default variables
PORT="11211"
USER="nobody"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""
RETVAL=0
prog="/usr/local/memcached/bin/memcached"
desc="Distributed memory caching"
lockfile="/var/lock/subsys/memcached"
start() {
echo-n $"Starting $desc (memcached): "
daemon $prog -d -p $PORT -u $USER -c $MAXCONN -m $CACHESIZE  $OPTIONS 
RETVAL=$? 
echo
[ $RETVAL -eq0 ] && touch$lockfile 
return$RETVAL 
}
stop() {
echo-n $"Shutting down $desc (memcached): "
killproc $prog 
RETVAL=$? 
echo
[ $RETVAL -eq0 ] && rm-f $lockfile 
return$RETVAL 
}
restart() {
stop 
start 
}
reload() {
echo-n $"Reloading $desc ($prog): "
killproc $prog -HUP 
RETVAL=$? 
echo
return$RETVAL 
}
case"$1"in
start) 
start 
;; 
stop) 
stop 
;; 
restart) 
restart 
;; 
condrestart) 
[ -e $lockfile ] && restart 
RETVAL=$? 
;;   
reload) 
reload 
;; 
status) 
status $prog 
RETVAL=$? 
;; 
*) 
echo$"Usage: $0 {start|stop|restart|condrestart|status}"
RETVAL=1 
esac

(9).增加执行权限

[[email protected] ~]# chmod +x /etc/init.d/memcached
(10).加入服务列表并设置开机自启动
[[email protected] ~]# chkconfig --add memcached
[[email protected] ~]# chkconfig memcached on 
[[email protected] ~]# chkconfig memcached --list 
memcached          0:关闭    1:关闭    2:启用    3:启用    4:启用    5:启用    6:关闭

(11).杀死所有memcached进程并重新启动memcached

[[email protected] ~]# killall memcached
[[email protected] ~]# service memcached start
Starting Distributed memory caching (memcached):           [确定]
[[email protected] ~]# netstat -ntulp
Active Internet connections (only servers) 
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Programname
tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN      8251/memcached
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1026/sshd
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1103/master
tcp        0      0 127.0.0.1:6010              0.0.0.0:*                   LISTEN      1137/sshd
tcp        0      0 127.0.0.1:6011              0.0.0.0:*                   LISTEN      8044/sshd
tcp        0      0 :::11211                    :::*                        LISTEN      8251/memcached
tcp        0      0 :::22                       :::*                        LISTEN      1026/sshd
tcp        0      0 ::1:25                      :::*                        LISTEN      1103/master
tcp        0      0 ::1:6010                    :::*                        LISTEN      1137/sshd
tcp        0      0 ::1:6011                    :::*                        LISTEN      8044/sshd
udp        0      0 0.0.0.0:11211               0.0.0.0:*                               8251/memcached
udp        0      0 :::11211                    :::*                                    8251/memcached

注,启动成功。还有点得说明,由于memcached的内存大小是手动设置的,有的时候需要随时去修改它,总不能每次都去修改memcached脚本吧,所以下面我们为memcached提供配置文件。

(12).为memcached脚本提供配置文件

[[email protected] ~]# vim /etc/sysconfig/memcached
PORT="11211"
USER="nobody"
MAXCONN="1024"
CACHESIZE="128"
OPTIONS=""

注,这里我们将内存大小改为了128M,方便我们测试对比。

(13).修改SysV的startup脚本载入配置文件

Memcache 应用详解

注,[ -f /etc/sysconfig/memcached ] && . /etc/sysconfig/memcached,加入这一行就行,我们先判断一下是否是文件,若是载入。

(14).测试一下

查看一下memcached内存大小

[[email protected] ~]# telnet 192.168.18.201 11211
Trying 192.168.18.201... 
Connected to 192.168.18.201. 
Escape character is '^]'. 
stats 
STAT pid 8251 
STAT uptime 852 
STAT time1378284537 
STAT version 1.4.15 
STAT libevent 2.0.21-stable 
STAT pointer_size 64 
STAT rusage_user 0.032994 
STAT rusage_system 0.033994 
STAT curr_connections 10 
STAT total_connections 11 
STAT connection_structures 11 
STAT reserved_fds 20 
STAT cmd_get 0 
STAT cmd_set 0 
STAT cmd_flush 0 
STAT cmd_touch 0 
STAT get_hits 0 
STAT get_misses 0 
STAT delete_misses 0 
STAT delete_hits 0 
STAT incr_misses 0 
STAT incr_hits 0 
STAT decr_misses 0 
STAT decr_hits 0 
STAT cas_misses 0 
STAT cas_hits 0 
STAT cas_badval 0 
STAT touch_hits 0 
STAT touch_misses 0 
STAT auth_cmds 0 
STAT auth_errors 0 
STAT bytes_read 7 
STAT bytes_written 0 
STAT limit_maxbytes 67108864 #大家可以看到,现在的内存限制是64M 
STAT accepting_conns 1 
STAT listen_disabled_num 0 
STAT threads 4 
STAT conn_yields 0 
STAT hash_power_level 16 
STAT hash_bytes 524288 
STAT hash_is_expanding 0 
STAT bytes 0 
STAT curr_items 0 
STAT total_items 0 
STAT expired_unfetched 0 
STAT evicted_unfetched 0 
STAT evictions 0 
STAT reclaimed 0 
END

重新启动一下memcached

[[email protected] ~]# service memcached restart
Shutting down Distributed memory caching (memcached):      [确定] 
Starting Distributed memory caching (memcached):           [确定]

我们再次查看一下内存大小

[[email protected] ~]# telnet 192.168.18.201 11211
Trying 192.168.18.201... 
Connected to 192.168.18.201. 
Escape character is '^]'. 
stats 
STAT pid 8279 #进程ID
STAT uptime 8000 #服务器运行秒数
STAT time1378284623 #服务器当前unix时间戳
STAT version 1.4.15 #服务器版本
STAT libevent 2.0.21-stable #libevent版本号
STAT pointer_size 64 #操作系统指针大小(这台服务器是64位的)
STAT rusage_user 0.000999 #进程累计用户时间
STAT rusage_system 0.003999 #进程累计系统时间
STAT curr_connections 10 #当前打开连接数
STAT total_connections 11 #曾打开的连接总数
STAT connection_structures 11 #服务器分配的连接结构数
STAT reserved_fds 20 #内部使用的FD数
STAT cmd_get 0 #执行get命令总数
STAT cmd_set 0 #执行set命令总数
STAT cmd_flush 0 #执行flush命令总数
STAT cmd_touch 0 #执行touch命令总数
STAT get_hits 0 #get命中次数
STAT get_misses 0 #get未命中次数
STAT delete_misses 0 #delete未命中次数
STAT delete_hits 0 #delete命中次数
STAT incr_misses 0 #incr未命中次数
STAT incr_hits 0 #incr命中次数
STAT decr_misses 0 #decr未命中次数
STAT decr_hits 0 #decr命中次数
STAT cas_misses 0 #cas未命中次数
STAT cas_hits 0 #cas命中次数
STAT cas_badval 0 #使用擦拭次数
STAT touch_hits 0 #touch命中次数
STAT touch_misses 0 #touch未命中次数
STAT auth_cmds 0 #认证处理的次数 
STAT auth_errors 0 #认证失败次数
STAT bytes_read 7 #读取字节总数
STAT bytes_written 0 #写入字节总数
STAT limit_maxbytes 134217728 #现在的内存大小为128M 
STAT accepting_conns 1 #目前接受的新接数
STAT listen_disabled_num 0 #失效的监听数
STAT threads 4 #当前线程数
STAT conn_yields 0 #连接操作主支放弃数目
STAT hash_power_level 16 #hash等级
STAT hash_bytes 524288 #当前hash表等级
STAT hash_is_expanding 0 #hash表扩展大小
STAT bytes 0 #当前存储占用的字节数
STAT curr_items 0 #当前存储数据总数
STAT total_items 0 #启动以来存储的数据总数
STAT expired_unfetched 0 #已过期但未获取的对象数目
STAT evicted_unfetched 0 #已驱逐但未获取的对象数目
STAT evictions 0 #LRU释放的对象数目
STAT reclaimed 0 #用已过期的数据条目来存储新数据的数目
END

注,大家可以看到,现在的内存大小为128M,说明我们配置文件修改成功。好了,到这里memcached的安装与配置到这里就基本完成了,下面我们来说一下php结合memcache的具体应用。

10.建立测试页面test.php

[[email protected] ~]# cd /data/www/   
[[email protected] www]# vim test.php    
<?php    
$mem = new Memcache;    
$mem->connect("192.168.18.202", 11211)  or die("Could not connect");
$version = $mem->getVersion();   
echo "Server's version: ".$version."<br/>\n";
$mem->set('testkey', 'Hello World', 0, 600) or die("Failed to save data at the memcached server");   
echo "Store data in the cache (data will expire in 600 seconds)<br/>\n";
$get_result = $mem->get('testkey');   
echo "$get_result is from memcached server.";        
?>

11.测试一下

Memcache 应用详解

注,测试成功。

12.php与memcache应用说明

memcached是高性能的分布式内存缓存服务器。 一般的使用php与memcache目的是,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度、 提高可扩展性。如下图,

Memcache 应用详解

好了,php与memcache的应用就说到这里,下面我们来说一下,nginx与memcache应用。

四、memcache 应用二 nginx与memcache

1.实验拓扑

Memcache 应用详解

2.memcached_module模块

nginx的memcached_module模块可以直接从memcached服务器中读取内容后输出,后续的请求不再经过应用程序处理,如php-fpm、django,大大的提升动态页面的速度。nginx只负责从memcached服务器中读取数据,要往memcached写入数据还得需要后台的应用程序来完成,主动的将要缓存的页面缓存到memcached中,可以通过404重定向到后端去处理的。    
ngx_http_memcached_module可以操作任何兼用memcached协议的软件。如ttserver、membase等。

结构图如下:

Memcache 应用详解

memcached的key可以通过memcached_key变量来设置,如以$uri。如果命中,那么直接输出内容,没有命中就意味着nginx需要从应用程序请求页面。同时,我们还希望该应用程序将键值对写入到memcached,以便下一个请求可以直接从memcached获取。如果键值不存在,nginx将报告not found错误。最好的方法是使用error_page指定和location请求处理。同时包含”Bad Gateway”错误和”Gateway Timeout”错误,如:error_page 404 502 504 = @app;。注意:需要设置default_type,否则可能会显示不正常。

3.模块说明

  • memcached_bind    
    语法: memcached_bind address | off;    
    默认值: none    
    配置段: http, server, location    
    指定从哪个IP来连接memcached服务器

  • memcached_buffer_size    
    语法: memcached_buffer_size size;    
    默认值: 4k|8k;    
    配置段: http, server, location    
    读取从memcached服务器接收到响应的缓冲大小。尽快的将响应同步传给客户端。

  • memcached_connect_timeout    
    语法:memcached_connect_timeout time;    
    默认值:60s;    
    配置段:http, server, location    
    与memcached服务器建立连接的超时时间。通常不超过75s。

  • memcached_gzip_flag    
    语法:memcached_gzip_flag flag;    
    默认值:none    
    配置段:http, server, location    
    测试memcached服务器响应标志。如果设置了,将在响应头部添加了Content-Encoding:gzip。

  • memcached_next_upstream    
    语法: memcached_next_upstream error | timeout | invalid_response | not_found | off …;    
    默认值: error timeout;    
    配置段: http, server, location    
    指定在哪些状态下请求将转发到另外的负载均衡服务器上,仅当memcached_pass有两个或两个以上时使用。

  • memcached_pass    
    语法:memcached_pass address:port or socket;    
    默认值:none    
    配置段:location, if in location    
    指定memcached服务器地址。使用变量$memcached_key为key查询值,如果没有相应的值则返回error_page 404。

  • memcached_read_timeout    
    语法:memcached_read_timeout time;    
    默认值:60s;    
    配置段:http, server, location    
    定义从memcached服务器读取响应超时时间。

  • memcached_send_timeout    
    语法:memcached_send_timeout    
    默认值:60s    
    配置段:http, server, location    
    设置发送请求到memcached服务器的超时时间。

用法:$memcached_key变量:memcached key的值。

4.nginx memcached的增强版ngx_http_enhanced_memcached_module

基于nginx memcached 模块的,添加的新特性有:

  • 自定义HTTP头,如Content-Type, Last-Modified。

  • hash键可超过250个字符,memcached受限。

  • 通过HTTP请求将数据存储到memcached。

  • 通过HTTP请求从memcached删除数据。

  • 通过HTTP请求清除所有memcached缓存数据。

  • 通过HTTP请求获取memcached状态数据。

  • 键名空间管理,来部分刷新缓存。

  • 缓存通过If-Modified-Since头和内容Last-Modified来回复304Not Modified请求。

5.安装nginx代理服务器

(1).解压源码包

[[email protected] src]# tar xf nginx-1.4.2.tar.gz
[[email protected] src]# cd nginx-1.4.2

(2).创建软链接

[[email protected] local]# ln -sv nginx-1.4.2 nginx
"nginx"-> "nginx-1.4.2"
[[email protected] local]# cd nginx 
[[email protected] nginx]# ll 
总用量 588 
drwxr-xr-x 6 1001 1001   4096 8月  29 17:32 auto 
-rw-r--r-- 1 1001 1001 222366 7月  17 20:51 CHANGES 
-rw-r--r-- 1 1001 1001 338680 7月  17 20:51 CHANGES.ru 
drwxr-xr-x 2 1001 1001   4096 8月  29 17:32 conf 
-rwxr-xr-x 1 1001 1001   2369 7月  17 20:51 configure 
drwxr-xr-x 3 1001 1001   4096 8月  29 17:32 contrib 
drwxr-xr-x 2 1001 1001   4096 8月  29 17:32 html 
-rw-r--r-- 1 1001 1001   1397 7月  17 20:51 LICENSE 
drwxr-xr-x 2 1001 1001   4096 8月  29 17:32 man
-rw-r--r-- 1 1001 1001     49 7月  17 20:51 README 
drwxr-xr-x 8 1001 1001   4096 8月  29 17:32 src

(3).新建nginx用户

[[email protected] nginx]# groupadd -g 108  -r nginx
[[email protected] nginx]# useradd -u 108 -r -g 108 nginx 
[[email protected] nginx]# id nginx 
uid=108(nginx) gid=108(nginx) 组=108(nginx)

(4).修改权限

[[email protected] nginx]# chown -R root:nginx /usr/local/nginx/*
[[email protected] nginx]# ll 
总用量 588 
drwxr-xr-x 6 root nginx   4096 8月  29 17:32 auto 
-rw-r--r-- 1 root nginx 222366 7月  17 20:51 CHANGES 
-rw-r--r-- 1 root nginx 338680 7月  17 20:51 CHANGES.ru 
drwxr-xr-x 2 root nginx   4096 8月  29 17:32 conf 
-rwxr-xr-x 1 root nginx   2369 7月  17 20:51 configure 
drwxr-xr-x 3 root nginx   4096 8月  29 17:32 contrib 
drwxr-xr-x 2 root nginx   4096 8月  29 17:32 html 
-rw-r--r-- 1 root nginx   1397 7月  17 20:51 LICENSE 
drwxr-xr-x 2 root nginx   4096 8月  29 17:32 man
-rw-r--r-- 1 root nginx     49 7月  17 20:51 README 
drwxr-xr-x 8 root nginx   4096 8月  29 17:32 src

(5).编译nginx

[[email protected] nginx]# yum -y install pcre-devel
[[email protected] nginx-1.4.2]# ./configure \
--prefix=/usr\ 
--sbin-path=/usr/sbin/nginx\ 
--conf-path=/etc/nginx/nginx.conf \ 
--error-log-path=/var/log/nginx/error.log \ 
--http-log-path=/var/log/nginx/access.log \ 
--pid-path=/var/run/nginx/nginx.pid  \ 
--lock-path=/var/lock/nginx.lock \ 
--user=nginx \ 
--group=nginx \ 
--with-http_ssl_module \ 
--with-http_flv_module \ 
--with-http_stub_status_module \ 
--with-http_gzip_static_module \ 
--http-client-body-temp-path=/var/tmp/nginx/client/\ 
--http-proxy-temp-path=/var/tmp/nginx/proxy/\ 
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/\ 
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi\ 
--with-pcre

注,编译过程中会出错,下面是错误信息。

错误1:

./configure: error: SSL modules require the OpenSSL library.
You can either donot enablethe modules, or installthe OpenSSL library 
into the system, or build the OpenSSL library statically from the source
with nginx by using --with-openssl=<path> option.

解决1:

[[email protected] nginx-1.4.2]# yum install -y openssl-devel

再来编译一下,

[[email protected] nginx-1.4.2]# ./configure   --prefix=/usr   --sbin-path=/usr/sbin/nginx   --conf-path=/etc/nginx/nginx.conf   --error-log-path=/var/log/nginx/error.log   --http-log-path=/var/log/nginx/access.log   --pid-path=/var/run/nginx/nginx.pid    --lock-path=/var/lock/nginx.lock   --user=nginx   --group=nginx   --with-http_ssl_module   --with-http_flv_module   --with-http_stub_status_module   --with-http_gzip_static_module   --http-client-body-temp-path=/var/tmp/nginx/client/   --http-proxy-temp-path=/var/tmp/nginx/proxy/   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi   --http-scgi-temp-path=/var/tmp/nginx/scgi   --with-pcre

出现在下面的选项说明编译成功,

Configuration summary
+ using system PCRE library 
+ using system OpenSSL library 
+ md5: using OpenSSL library 
+ sha1: using OpenSSL library 
+ using system zlib library
nginx path prefix: "/usr"
nginx binary file: "/usr/sbin/nginx"
nginx configuration prefix: "/etc/nginx"
nginx configuration file: "/etc/nginx/nginx.conf"
nginx pid file: "/var/run/nginx/nginx.pid"
nginx error log file: "/var/log/nginx/error.log"
nginx http access log file: "/var/log/nginx/access.log"
nginx http client request body temporary files: "/var/tmp/nginx/client/"
nginx http proxy temporary files: "/var/tmp/nginx/proxy/"
nginx http fastcgi temporary files: "/var/tmp/nginx/fcgi/"
nginx http uwsgi temporary files: "/var/tmp/nginx/uwsgi"
nginx http scgi temporary files: "/var/tmp/nginx/scgi"
[[email protected] nginx-1.4.2]# make && make install

(6).为nginx提供SysV init脚本

[[email protected] nginx-1.4.2]# vim  /etc/init.d/nginx
#!/bin/sh 
# 
# nginx - this script starts and stops the nginx daemon 
# 
# chkconfig:   - 85 15 
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \ 
#               proxy and IMAP/POP3 proxy server 
# processname: nginx 
# config:      /etc/nginx/nginx.conf 
# config:      /etc/sysconfig/nginx 
# pidfile:     /var/run/nginx.pid 
# Source function library. 
. /etc/rc.d/init.d/functions
# Source networking configuration. 
. /etc/sysconfig/network
# Check that networking is up. 
[ "$NETWORKING"= "no"] && exit0 
nginx="/usr/sbin/nginx"
prog=$(basename$nginx) 
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() { 
# make required directories 
user=`nginx -V 2>&1 | grep"configure arguments:"| sed's/[^*]*--user=\([^ ]*\).*/\1/g'-` 
options=`$nginx -V 2>&1 | grep'configure arguments:'` 
foropt in$options; do
if[ `echo$opt | grep'.*-temp-path'` ]; then
value=`echo$opt | cut-d "="-f 2` 
if[ ! -d "$value"]; then
# echo "creating" $value 
mkdir-p $value && chown-R $user $value 
fi
fi
done
} 
start() { 
[ -x $nginx ] || exit5 
[ -f $NGINX_CONF_FILE ] || exit6 
make_dirs 
echo-n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE 
retval=$? 
echo
[ $retval -eq0 ] && touch$lockfile 
return$retval 
} 
stop() { 
echo-n $"Stopping $prog: "
killproc $prog -QUIT 
retval=$? 
echo
[ $retval -eq0 ] && rm-f $lockfile 
return$retval 
} 
restart() { 
configtest || return$? 
stop 
sleep1 
start 
} 
reload() { 
configtest || return$? 
echo-n $"Reloading $prog: "
killproc $nginx -HUP 
RETVAL=$? 
echo
} 
force_reload() { 
restart 
} 
configtest() { 
$nginx -t -c $NGINX_CONF_FILE 
} 
rh_status() { 
status $prog 
} 
rh_status_q() { 
rh_status >/dev/null2>&1 
} 
case"$1"in
start) 
rh_status_q && exit0 
$1 
;; 
stop) 
rh_status_q || exit0 
$1 
;; 
restart|configtest) 
$1 
;; 
reload) 
rh_status_q || exit7 
$1 
;; 
force-reload) 
force_reload 
;; 
status) 
rh_status 
;; 
condrestart|try-restart) 
rh_status_q || exit0 
;; 
*) 
echo$"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit2 
esac

(7).为此脚本赋予执行权限

[[email protected] ~]# chmod +x /etc/init.d/nginx

(8).添加至服务管理列表,并让其开机自动启动

[[email protected]eb ~]# chmod +x /etc/init.d/nginx
[[email protected] ~]# chkconfig --add nginx 
[[email protected] ~]# chkconfig nginx on 
[[email protected] ~]# chkconfig --list nginx 
nginx              0:关闭    1:关闭    2:启用    3:启用    4:启用    5:启用    6:关闭

(9).启动nginx

[[email protected] ~]# service nginx start
正在启动 nginx:                                           [确定]

(10).查看一下端口号    

[[email protected] ~]# netstat -ntulp 
Active Internet connections (only servers) 
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Programname
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      4801/nginx
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1033/sshd
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1110/master
tcp        0      0 127.0.0.1:6010              0.0.0.0:*                   LISTEN      1144/sshd
tcp        0      0 127.0.0.1:6011              0.0.0.0:*                   LISTEN      1203/sshd
tcp        0      0 :::22                       :::*                        LISTEN      1033/sshd
tcp        0      0 ::1:25                      :::*                        LISTEN      1110/master
tcp        0      0 ::1:6010                    :::*                        LISTEN      1144/sshd
tcp        0      0 ::1:6011                    :::*                        LISTEN      1203/sshd

(11).测试访问一下

Memcache 应用详解

好了,到这里nginx的安装全部完成,下面我们来看一下nginx的配置文件。

6.nginx整合memcache

server {   
        listen       80;    
        server_name  www.test.com;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {   
                set $memcached_key $uri;    
                memcached_pass     192.168.18.202:11211;    
                default_type       text/html;    
                error_page         404 @fallback;    
        }
        location @fallback {   
                proxy_pass http://192.168.18.201;
        }    
}

从上面的配置文件我们可以看出,一个请求到达后,会其uri作为key去Memcached服务器192.168.18.202:11211上查找value,如果没有命中,则返回404。这时通过error_page将404接收转到@fallback,返回给Web服务去处理请求。

五、memcache 应用三 session与memcache

1.实验拓扑

Memcache 应用详解

2.配置Web1与Web2安装php memcache扩展

注,上面已经演示过怎么安装php memcache扩展,这里就不再演示。

3.安装memcache服务器

注,同上大家自己安装一下。

4.修改php配置文件

[[email protected] ~]# vim /etc/php.ini
session.save_handler = memcache  
session.save_path = "tcp://192.168.18.203:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

5.增加测试页面

说明:新建php页面setsess.php,为客户端设置启用session。

<?php  
session_start();   
if (!isset($_SESSION['www.MageEdu.com'])) {   
  $_SESSION['www.MageEdu.com'] = time();   
}   
print $_SESSION['www.MageEdu.com'];   
print "<br><br>";   
print "Session ID: " . session_id();   
?>
说明:新建php页面showsess.php,获取当前用户的会话ID。
<?php  
session_start();   
$memcache_obj = new Memcache;   
$memcache_obj->connect('172.16.200.11', 11211);   
$mysess=session_id();   
var_dump($memcache_obj->get($mysess));   
$memcache_obj->close();   
?>

注,两台Web服务器获得的session id一致。

六、memcache 图形管理工具

1.解压memadmin

[[email protected] ~]# cd src/  
[[email protected] src]# tar xf memadmin-1.0.12.tar.gz    
[[email protected] src]# cd memadmin   
[[email protected] memadmin]# ls   
apps  config.php  p_w_picpaths  include  index.php  langs  LICENSE.txt  README.txt  views

2.移动memadmin到页面目录下

[[email protected] src]# mv memadmin /data/www/  
[[email protected] src]# cd /data/www/   
[[email protected] www]# ls   
index.html  index.php  memadmin  test.php

3.查看一下配置文件

[[email protected] memadmin]# vim config.php
<?php  
if (!defined('IN_MADM')) exit();
$config['user'] = "admin"; // your username  
$config['passwd'] = "admin"; // your password

注,大家可以看到默认的用户名是admin,密码是admin。

4.下面我们来登录一下

Memcache 应用详解

5.登录并演示

注,修改memcached服务器的IP与端口,我这里是192.168.11.202,端口是默认11211。

Memcache 应用详解

注,点击 “高级参数”,选择 “持久化连接”,我这里设置是30s。最后,点击增加按钮。

Memcache 应用详解

注,点击默认连接,就可以看到我们设置的参数,点击“开始管理”,进入管理界面。

Memcache 应用详解

注,进入管理界面。进入的第一个页面是“连接参数”页面。由于memadmin工具使用简单,我在这里就不详细讲解了。大家自己看一下!

Memcache 应用详解

好了,到这里memcached的应用讲解,全部完成了。最后想说,希望大家有所收获^_^……