传统上基于进程或线程模型架构的web服务通过每进程或每线程处理并发连接请求,这势必会在网络和I/O操作时产生阻塞,其另一个必然结果则是对内存或CPU的利用率低下。生成一个新的进程/线程需要事先备好其运行时环境,这包括为其分配堆内存和栈内存,以及为其创建新的执行上下文等。这些操作都需要占用CPU,而且过多的进程/线程还会带来线程抖动或频繁的上下文切换,系统性能也会由此进一步下降。 在设计的最初阶段,nginx的主要着眼点就是其高性能以及对物理计算资源的高密度利用,因此其采用了不同的架构模型。受启发于多种操作系统设计中基于“事件”的高级处理机制,nginx采用了模块化、事件驱动、异步、单线程及非阻塞的架构,并大量采用了多路复用及事件通知机制。在nginx中,连接请求由为数不多的几个仅包含一个线程的进程worker以高效的回环(run-loop)机制进行处理,而每个worker可以并行处理数千个的并发连接及请求。 如果负载以CPU密集型应用为主,如SSL或压缩应用,则worker数应与CPU数相同;如果负载以IO密集型为主,如响应大量内容给客户端,则worker数应该为CPU个数的1.5或2倍。 Nginx会按需同时运行多个进程:一个主进程(master)和几个工作进程(worker),配置了缓存时还会有缓存加载器进程(cache loader)和缓存管理器进程(cache manager)等。所有进程均是仅含有一个线程,并主要通过“共享内存”的机制实现进程间通信。主进程以root用户身份运行,而worker、cache loader和cachemanager均应以非特权用户身份运行。 主进程主要完成如下工作: 1. 读取并验正配置信息; 2. 创建、绑定及关闭套接字; 3. 启动、终止及维护worker进程的个数; 4. 无须中止服务而重新配置工作特性; 5. 控制非中断式程序升级,启用新的二进制程序并在需要时回滚至老版本; 6. 重新打开日志文件,实现日志滚动; 7. 编译嵌入式perl脚本; worker进程主要完成的任务包括: 1. 接收、传入并处理来自客户端的连接; 2. 提供反向代理及过滤功能; 3. nginx任何能完成的其它任务; cache loader进程主要完成的任务包括: 1. 检查缓存存储中的缓存对象; 2. 使用缓存元数据建立内存数据库; cache manager进程的主要任务: 1. 缓存的失效及过期检验; Nginx的配置有着几个不同的上下文:main、http、server、upstream和location(还有实现邮件服务反向代理的mail)。配置语法的格式和定义方式遵循所谓的C风格,因此支持嵌套,还有着逻辑清晰并易于创建、阅读和维护等优势。 Nginx的代码是由一个核心和一系列的模块组成, 核心主要用于提供WebServer的基本功能,以及Web和Mail反向代理的功能;还用于启用网络协议,创建必要的运行时环境以及确保不同的模块之间平滑地进行交互。不过,大多跟协议相关的功能和某应用特有的功能都是由nginx的模块实现的。这些功能模块大致可以分为事件模块、阶段性处理器、输出过滤器、变量处理器、协议、upstream和负载均衡几个类别,这些共同组成了nginx的http功能。事件模块主要用于提供OS独立的(不同操作系统的事件机制有所不同)事件通知机制如kqueue或epoll等。协议模块则负责实现nginx通过http、tls/ssl、smtp、pop3以及imap与对应的客户端建立会话。 在nginx内部,进程间的通信是通过模块的pipeline或chain实现的;换句话说,每一个功能或操作都由一个模块来实现。例如,压缩、通过FastCGI或uwsgi协议与upstream服务器通信,以及与memcached建立会话等。 
配置nginx作为web_Server使用
安装nginx
# mkdir  /data/software  -pv
# cd/data/software/
# wget http://nginx.org/download/nginx-1.6.2.tar.gz
安装之前先安装一些基本的库和依赖包
# yum install gccgcc-c++  openssl-devel pcre pcre-develzlib zlib-devel
创建web用户:
# groupadd  -r nginx
# useradd  -r -g nginx -s /bin/false  -M nginx
# tar zxvfnginx-1.6.2.tar.gz
# cd nginx-1.6.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
备注:--with-pcre 如果出现异常,可以去掉此参数尝试
# make &&make install && echo "install nginx ok"
检查配置文件:
# /usr/sbin/nginx–t
使用-V参数查看编译参数:
# /usr/sbin/nginx–V
启动nginx
使用以下脚本:
vim/etc/init.d/nginx
#!/bin/sh
#
# nginx - thisscript 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 functionlibrary.
./etc/rc.d/init.d/functions
 
# Sourcenetworking configuration.
./etc/sysconfig/network
 
# Check thatnetworking 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
 
# chmod  +x /etc/init.d/nginx
# chkconfig  --add nginx
# chkconfig  nginx on
# service nginxstatus
# service nginxstart
# service nginxrestart
IE访问:
安装MySQL(通用二进制包)
# cd/data/software/
# groupadd  -r mysql
# useradd  -g mysql -r -s /sbin/nologin  -M -d /mydata/data mysql
# chown  -R mysql:mysql /mydata/data
# tar zxvfmysql-5.5.40-linux2.6-x86_64.tar.gz -C /usr/local/
# cd /usr/local/
# ln -svmysql-5.5.40-linux2.6-x86_64/ mysql
# cd mysql
# chownmysql:mysql ./ -R
#./scripts/mysql_install_db --user=mysql --datadir=/mydata/data/
# cpsupport-files/my-large.cnf  /etc/my.cnf
编辑my.cnf在mysqld组中添加:datadir=/mydata/data
log-error=/mydata/data/mysql-error.log
# cpsupport-files/mysql.server /etc/rc.d/init.d/mysqld
# chkconfig  --add mysqld
# chkconfig  mysqld on
# service mysqldstart
输出mysqld man手册的路径
# vim/etc/man.config
MANPATH/usr/local/mysql/man
输出头文件的路径
# ln -sv/usr/local/mysql/include /usr/local/mysql
输出mysqld库文件路径
# echo"/usr/loca/mysql/lib" > /etc/ld.so.conf.d/mysql.conf
# ldconfig  -v
安装PHP
# cd/data/software/
# wget http://cn2.php.net/distributions/php-5.5.18.tar.gz
# wget http://ncu.dl.sourceforge.net/project/mcrypt/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.gz
# wget http://ncu.dl.sourceforge.net/project/mhash/mhash/0.9.9.9/mhash-0.9.9.9.tar.bz2# wget http://ncu.dl.sourceforge.net/project/mcrypt/MCrypt/2.6.8/mcrypt-2.6.8.tar.gz# tar zxvf libmcrypt-2.5.8.tar.gz
# cdlibmcrypt-2.5.8# ./configure# make && make install
# tar jxvfmhash-0.9.9.9.tar.bz2# cd mhash-0.9.9.9# ./configure
# make &&make install# tar zxvf mcrypt-2.6.8.tar.gz# cd mcrypt-2.6.8
# echo"/usr/local/lib" >> /etc/ld.so.conf && ldconfig -v# ./configure# vim configure
19744 #    $RM "$cfgfile" 注释掉此行
# make &&make install
 
# tar zxvfphp-5.5.18.tar.gz
# cd php-5.5.18
# ./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
# make &&make install
# cpphp.ini-production  /etc/php.ini# cp sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm# chmod  +x /etc/rc.d/init.d/php-fpm# chkconfig  --add php-fpm# chkconfig  php-fpm on# cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf# vim /usr/local/php/etc/php-fpm.conf
配置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(这个参数可以不用)
# service php-fpmstart
# lsof -i :9000
整个PHP5和nginx
Nginx vim/etc/nginx/nginx.conf
启用以下选项:
location ~ \.php${
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi_params;
        }
# cat/etc/nginx/fastcgi_params
fastcgi_paramGATEWAY_INTERFACE CGI/1.1;
fastcgi_paramSERVER_SOFTWARE nginx;
fastcgi_paramQUERY_STRING $query_string;
fastcgi_paramREQUEST_METHOD $request_method;
fastcgi_paramCONTENT_TYPE $content_type;
fastcgi_paramCONTENT_LENGTH $content_length;
fastcgi_paramSCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_paramSCRIPT_NAME $fastcgi_script_name;
fastcgi_paramREQUEST_URI $request_uri;
fastcgi_paramDOCUMENT_URI $document_uri;
fastcgi_paramDOCUMENT_ROOT $document_root;
fastcgi_paramSERVER_PROTOCOL $server_protocol;
fastcgi_paramREMOTE_ADDR $remote_addr;
fastcgi_paramREMOTE_PORT $remote_port;
fastcgi_paramSERVER_ADDR $server_addr;
fastcgi_paramSERVER_PORT $server_port;
fastcgi_paramSERVER_NAME $server_name;并在所支持的主页面格式中添加php格式的主页,类似如下: 
location / {
root html;
index index.phpindex.html index.htm;
}
创建测试页面:
# mkdir -pv/website/data
# cat >>/website/data/index.php <<EOF
> <?
> phpinfo();
> ?>
> EOF
Nginx.conf修改
        location / {
            root   /website/data;
            index  index.php index.html index.htm;
        }
备注:这里遇到以下问题:
问题1:52055#0: *1 FastCGI sent in stderr: "Primary script unknown" whilereading response header from upstream
将:fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
改为:fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;nginx识别不到/scripts路径,所以phpinfou验证信息无法正成通过。改成如上就是:$document_root就是针对/website/data目录下的php文件进行解析。
问题2:
一切正常之后发现phpininfo的页面为空白页
修改vim /etc/php.ini
short_open_tag =On访问一切正常:
安装xcache,为PHP加速
# cd/data/software/
# wget http://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz
# tar zxvfxcache-3.2.0.tar.gz
# cd xcache-3.2.0
#/usr/local/php/bin/phpize
#./configure  --enable-xcache--with-php-config=/usr/local/php/bin/php-config
# make &&make install
# mkdir -p/etc/php.d# cp xcache.ini  /etc/php.d/# vim /etc/php.d/xcache.iniextension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/xcache.so
指定具体的路径
# service php-fpmrestart
 
 
Nginx虚拟主机的配置:
server {
     listen    8080;
     server_name localhost;
     location /bbs {
           root /website;
           index index.html index.htmindex.php;
           }
    error_page 404 /404.html;
    location = /404.html {
           root /website/bbs;
           }
}
这里定义了一个虚拟主机,访问:http://xxx.xxx.xxx.xxx:8080/bbs,实际访问的是:http://xxx.xxx.xxx.xxx:8080/website/bbs目录
404错误页面重定向,可以隐藏版本信息,正常页面如下:需要在HTTP区域开启:fastcgi_intercept_errors on; 选项然后在server中配置好:error_page     404 /404.html;
location =/404.html {
        root /website/bbs;
       }
error_page     404 /404.html;
error_page       502 503 504 /50x.html;
error_page       403 http://xxx.xxx.xxx.xxx/forbidden.html;
# error_page   404 =@fetch;
location =/404.html {
        root /website/bbs;
       }
 
 
Upstream 模块
Upstream backup {
         Server www.xxx.com weight=5;
         Server www.xxx.com :8080
         Server www.xxx.com down; #所有服务器挂了之后,会把请求交给此服务器
         Ip_hash; #开启回话保持机制
}
这里nginx支持三种会话机制:
         Round-robin
         Ip_hash
         Least_conn
 
配置nginx做反向代理服务器
这里需要两台web node1 node2
配置nginx配置文件:
HTTP区域定义:    upstream webserver {
        server 172.16.100.101:80 weight=1;
        server 172.16.100.102:80 weight=1;
     }
server {
        listen       80;
        server_name  localhost;
        location / {
             proxy_pass http://webserver;
        }
}
# nginx –t&& service nginx restart
实现负载均衡
URL重写
如下:
Server {
         Listen 8080;
         Server_name localhost;
         Location / {
                   Root html;
                   Index index.html;
                   Rewrite^/bbs/(.*)$ http://172.16.100.101/form/$1;
}
Error_page 404/404.html;
Localtion =/404.html {
Root html;
}
}
确保后端可以正常访问:
IE访问:http://172.16.100.128:8080/bbs/
server {
         listen 8080;
         server_name localhost;
         location / {
                root html;
                index index.html index.htmindex.php;
                rewrite^/bbs/(.*)$ /forum/$1;
                }
    }
访问http://172.16.100.128:8080/bbs/ 跳转到http://172.16.100.128:8080/forum
Bbs目录不存在,这里是实现的是本机跳转。
 
Last :本次重写完成,重启协下一轮检查
Break:本次重写结束后,直接后续操作
 
 
常用指令使用:alias 指令:
         Location /bbs/ {
         alias /website/bbs/;
         index index.html index.htm;
}访问http://xxx.xxx.xxx.xxx/bbs/index.html重定向到http://xxx.xxx.xxx.xxx/website/bbs/index.html;
Location指令:
         Location /bbs/ {
         Root /website/;         index index.html index.htm;
}
访问http://xxx.xxx.xxx.xxx/bbs/ 实际访问是
http://xxx.xxx.xxx.xxx/website/bbs;
注意两者的区别
 
HTTP access 模块:
 
 
 
 
Nginx缓存机制:
nginx 缓存:
        cache:共享内存,存储键和缓存对象元数据
                        磁盘空间,存储数据
        proxy_cache_path:    不能定义在server{}中
缓存目录,子目录级别
proxy_cache_path/nginx/cache/first level=1:2:1 keys_zone=first:20m max_size=1G;
 
cache_manager:LRU
 
配置如下:
HTTP区域配置:http {
proxy_cache_path/nginx/cache/first levels=1:2:1 keys_zone=first:20m max_size=1g;
}
Server {
add_header X-Cache "$upstream_cache_status from$server_addr";
location  / {
                             proxy_pass http://webserver;
             proxy_set_header Host      $host;
             proxy_set_header X-Real-IP$remote_addr;
             proxy_cache first;
             proxy_cache_valid 200 10m
}
}
 
 
另外三个常用的缓存:
Open_log_cache:日志缓存
Open_file_cache:
Fastcgi_cache:
 
 
压缩功能:
gzip on;gzip_min_lenght      1000;gzip_proxied    expired no-cache no-storeprivate auth;gzip_types        text/plain          application/xml;
 
 
 
nginx 实现动静分离
 
upstream phpsrvs{
server 172.16.100.101:80 weight=1;
server 172.16.100.102:80 weight=1;
}
Upstream imgsrvs{
         Server 172.16.100.103:80 weight=1;
         Server 172.16.100.103:80 weight=1;
}
http {
server {
                   location / {
         root/web/htdocs;                   index index.phpindex.html;
}
                   Location ~*\.php${
         Fastcgi_passhttp://phpsrvs;
}
Location ~*”\.(jpg|jpeg|jif|png)$” {
         Proxy_passhttp://imgsrvs;
}
}
}
 
 
安装memcached
# cd/data/software/
# wget https://cloud.github.com/downloads/libevent/libevent/libevent-1.4.14b-stable.tar.gz# wget http://memcached.org/files/memcached-1.4.21.tar.gz
# tar zxvflibevent-1.4.14b-stable.tar.gz# cd libevent-1.4.14b-stable
#./configure  --prefix=/usr/local/libevent# make && make install
# tar zxvfmemcached-1.4.21.tar.gz# cd memcached-1.4.21# ./configure  --enable-sasl--prefix=/usr/local/memcached --with-libevent=/usr/local/libevent# make && make install
memcached的常用选项说明
-l<ip_addr>:指定进程监听的地址;
-d: 以服务模式运行;
-u<username>:以指定的用户身份运行memcached进程;
-m <num>:用于缓存数据的最大内存空间,单位为MB,默认为64MB;
-c <num>:最大支持的并发连接数,默认为1024;
-p <num>: 指定监听的TCP端口,默认为11211;
-U <num>:指定监听的UDP端口,默认为11211,0表示关闭UDP端口;
-t<threads>:用于处理入站请求的最大线程数,仅在memcached编译时开启了支持线程才有效;
-f <num>:设定Slab Allocator定义预先分配内存空间大小固定的块时使用的增长因子;
-M:当内存空间不够使用时返回错误信息,而不是按LRU算法利用空间;
-n: 指定最小的slab chunk大小;单位是字节;
-S: 启用sasl进行用户认证
启动memcached
#/usr/local/memcached/bin/memcached  -m128 -n 20 -f 1.1 -vv -u nobody –d
Memcached操作:
telnet      localhost           11211
add mykey 0 12 5
hello
get mykey
 
memcached启动脚本:
#!/bin/bash
#
# Init file formemcached
#
# chkconfig: - 8614
# description:Distributed memory caching daemon
#
# processname:memcached
# config:/etc/sysconfig/memcached
 
./etc/rc.d/init.d/functions
 
## Defaultvariables
PORT="11211"
USER="nobody"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""
 
RETVAL=0
prog="/usr/local/memcached/bin/memcached"
desc="Distributedmemory caching"
lockfile="/var/lock/subsys/memcached"
 
start() {
        echo -n $"Starting $desc(memcached): "
        daemon $prog -d -p $PORT -u $USER -c$MAXCONN -m $CACHESIZE -o "$OPTIONS"
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch$lockfile
        return $RETVAL
}
 
stop() {
        echo -n $"Shutting down $desc(memcached): "
        killproc $prog
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && 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
 
exit $RETVAL
 
# chmod  +x /etc/rc.d/init.d/memcached # chkconfig  --add memcached
# servicememcached start
 
动态修改使用内存:
# cat/etc/sysconfig/memcached
PORT="11211"
USER="nobody"
MAXCONN="1024"
CACHESIZE="128"
OPTIONS=""
编辑/etc/init.d/memcached
## Defaultvariables
PORT="11211"
USER="nobody"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""
[ -f/etc/sysconfig/memcached  ] && ./etc/sysconfig/memcached
此行即可
安装memcached的php扩展
# cd /data/software/# wget http://pecl.php.net/get/memcache-2.2.7.tgz# wget https://codeload.github.com/junstor/memadmin/zip/master
# tar zxvfmemcache-2.2.7.tgz# cd memcache-2.2.7# /usr/local/php/bin/phpize# ./configure --with-php-config=/usr/local/php/bin/php-config  --enable-memcache# make && make install# cat /etc/php.d/memcache.ini
extension =/usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/memcache.so
[root@localhostmemcache-2.2.7]#
# service php-fpm restart
测试php使用memcached
# cat/website/data/test.php
<?php
$mem = newMemcache;
$mem->connect("127.0.0.1",11211)  or die("Could notconnect");
 
$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 memcachedserver");
echo "Storedata in the cache (data will expire in 600 seconds)<br/>\n";
 
$get_result =$mem->get('testkey');
echo"$get_result is from memcached server.";        
?>
[root@localhostmemcache-2.2.7]#
证明PHP程序已经可以使用memcached
 
Nginx 整个memcached
    upstream webserver {
        server 172.16.100.101:80 weight=1;
        server 172.16.100.102:80 weight=1;
     }
    server {
        listen       80;
        server_name  localhost;
        location / {
             set $memcached_key $uri;
             memcached_pass 127.0.0.1:11211;
             default_type text/html;
             error_page 404 @fallback;
        }
        location @fallback {
                proxy_pass http://webserver;
                proxy_set_header Host      $host;
                proxy_set_header X-Real-IP$remote_addr;
        }
配置memadmin-master
# unzipmemadmin-master.zip# mv memadmin-master /website/data/memadminhttp://172.16.100.128:8080/memadmin 
 
配置memcached缓存mysqld数据
Memcached 和MySQL都已经安装完成
CREATE DATABASEmem_test;
USE men_test;
CREATE TABLE mem( id int(7) NOT NULL AUTO_INCREMENT, name char(8) DEFAULT NULL, PRIMARY KEY(id) ) ENGINE=innodb AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
INSERT INTOmem  VALUES(1,'tome'),(2,'james'),(3,'jack'),(4,'mary'),(5,'zhang'),(6,'lisi'),(7,'wangwu'),(8,'hello'),(9,'huhu');
 
GRANT SELECT ONmem.* to memcache@'%' IDENTIFIED BY '123456';
FLUSH PRIVILEGES;
创建PHP测试页面:
# cat/website/data/memcache.php
<?php
$memcachehost ='127.0.0.1';
$memcacheport =11211;
$memcachelife =60;
$memcache = newMemcache;
$memcache->connect($memcachehost,$memcacheport)or die ("Could not connect");
$query="select* from mem limit 10";
$key=md5($query);
if(!$memcache->get($key))
{
               $conn=mysql_connect("127.0.0.1","memcache","12345");
                mysql_select_db(memcache_test);
                $result=mysql_query($query);
                while($row=mysql_fetch_assoc($result))
                {
                        $arr[]=$row;
                }
                $f = 'mysql';
                $memcache->add($key,serialize($arr),0,30);
                $data = $arr ;
}
else{
        $f = 'memcache';
        $data_mem=$memcache->get($key);
        $data = unserialize($data_mem);
}
echo $f;
echo"<br>";
echo"$key";
echo"<br>";
//print_r($data);
foreach($data as$a)
{
                echo "number is<b><font color=#FF0000>$a[id]</font></b>";
                echo "<br>";
                echo "name is<b><font color=#FF0000>$a[name]</font></b>";
                echo "<br>";
 
}
?>
[root@localhostdata]#
首次访问:说明是从MySQL中访问的数据,再次刷新看看:说明从memcached取到的数据,记住ID进行查询下