Nginx + MySQL + PHP + Xcache + Memcached

傳統上基於進程或線程模型架構的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

wKiom1Ri9MTgW7CDAAQTfh87qIg466.jpg

啓動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
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訪問:
wKioL1Ri9USSmpdxAAHbq-w0pxo040.jpg


安裝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.cnfmysqld組中添加:

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

整個PHP5nginx

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;
        }

並在所支持的主頁面格式中添加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

訪問一切正常:

wKioL1Ri9Vng4LsxAAIgnIcrM64787.jpg

安裝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.ini
extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20121212/xcache.so

指定具體的路徑

service php-fpmrestart

wKioL1Ri9WzxnLjbAADx5pGno6M901.jpg

 

 

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錯誤頁面重定向,可以隱藏版本信息,正常頁面如下:
wKioL1Ri9YWBxOKDAABcA5jFrC8868.jpg需要在HTTP區域開啓:
fastcgi_intercept_errors on; 選項
然後在server中配置好:

error_page     404 /404.html;
location =/404.html {
        root /website/bbs;
       }

wKiom1Ri9S-xT-UXAADHMXZc4zs261.jpg

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

wKioL1Ri9fWg99lEAACp2YQiskk577.jpg


wKioL1Ri9iGz8ZLtAACp3tIV2HA563.jpg

實現負載均衡

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;
}
}

確保後端可以正常訪問:
wKioL1Ri9kuAFfjEAADzpnORoTM740.jpg

IE訪問:
http://172.16.100.128:8080/bbs/

wKioL1Ri9mqBzIzFAAKyXSlEr5Q729.jpg

wKioL1Ri9n7T9ixQAACu4WPAF1M864.jpg

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
}
}

 

wKiom1Ri9jbhshW8AAJAt7gCwhE377.jpg

 

另外三個常用的緩存:

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端口,默認爲112110表示關閉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

wKioL1Ri9szjWNYJAANKSm06IFc356.jpg

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

此行即可

安裝memcachedphp擴展

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
[[email protected]]#
service php-fpm restart

wKioL1Ri9t2wTFEDAAHNHgEBqOQ581.jpg

測試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.";        
?>

[[email protected]]#

wKioL1Ri9vKx7t60AAFYCB7B9kg500.jpgwKiom1Ri9pXDGAeRAAFbdnXNUxU471.jpg

證明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/memadmin
http://172.16.100.128:8080/memadmin

wKioL1Ri9xXyh05GAAH_C-1emrA268.jpg

 

配置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 ON mem.* 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]#

首次訪問:
wKiom1Ri9ryz62tvAAHVcZRBRN0862.jpg說明是從MySQL中訪問的數據,再次刷新看看:
wKiom1Ri9uyRgmPbAAG9W064sBg975.jpg說明從memcached取到的數據,記住ID進行查詢下

wKiom1Ri9z3zRdsnAAIdzY4Quw8739.jpg

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章