天天看點

菜鳥學Linux 第098篇筆記 memcached

菜鳥學Linux 第098篇筆記 memcached

内容總覽

memcached 緩存伺服器

memcached 安裝與配置

配置php調用memcached

配置php将會話儲存至memcached中

圖形化的memcached監控和管理工具

memcached 緩存伺服器,但本身無法決定緩存任何資料

一半依賴于用戶端,一半依賴于伺服器

LRU 最近最少使用

記憶體緩存伺服器 最小不能少于48bytes 最大1mb

bubby system 夥伴系統   避免記憶體外碎片

slab allocator (slab配置設定器)  避免記憶體内碎片

memcached: 不通信分布式緩存伺服器

port 11211

memcached用戶端庫程式

perl module

cache::memcached

php

memcache

memcached

c/c++

libmemcached

memadmin (圖形化來管理和檢視)

準備工作 下載下傳memcached libevent 安裝memcached時有依賴libevent

1.  安裝libevent 和 memcached

安裝libevent

# tar -xf libevent-2.1.8-stable.tar.gz

# cd libevent-2.1.8-stable

# ./configure --prefix=/usr/local/libevent

# make && make install

安裝memcached

# tar xf memcached-1.4.34.tar.gz

# cd memcached-1.4.34

# ./configure --prefix=/usr/local/memcacled --with-libevent=/usr/local/libevent/

(到此安裝完成)

2. 配置memcached

memcached指令

-p <num>      TCP port number to listen on (default: 11211)

-U <num>      UDP port number to listen on (default: 11211, 0 is off)

-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

-u <username> assume identity of <username> (only when run as root)

-m <num>      max memory to use for items in megabytes (default: 64 MB)

-f <factor>   chunk size growth factor (default: 1.25)

-n <bytes>    minimum space allocated for key+value+flags (default: 48)

# /usr/local/memcacled/bin/memcached -m 128 -n 20 -f 1.2 -vv -u nobody -d

3. 測試memcached

add 指令

add keyname flag timeout datasize

add firstkey 0 20 5

hello

get 指令

get firstkey

# telnet localhost 11211

(此時memcached可以正常工作了)

4. 添加服務腳本為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=""

[ -f /etc/sysconf/memcached ] && . /etc/sysconfig/memcached

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 -eq 0 ] && touch $lockfile

        return $RETVAL

}

stop() {

        echo -n $"Shutting down $desc (memcached): "

        killproc $prog

        [ $RETVAL -eq 0 ] && rm -f $lockfile

restart() {

        stop

        start

reload() {

        echo -n $"Reloading $desc ($prog): "

        killproc $prog -HUP

case "$1" in

  start)

        ;;

  stop)

  restart)

        restart

  condrestart)

        [ -e $lockfile ] && restart

        ;;       

  reload)

        reload

  status)

        status $prog

   *)

        echo $"Usage: $0 {start|stop|restart|condrestart|status}"

        RETVAL=1

esac

exit $RETVAL

添加可執行

1. 安裝php

所依賴的安裝包

libmcrypt-2.5.8-4.el5.centos.i386.rpm

libmcrypt-devel-2.5.8-4.el5.centos.i386.rpm

mhash-0.9.9-1.el5.centos.i386.rpm

mhash-devel-0.9.9-1.el5.centos.i386.rpm

mcrypt-2.6.8-1.el5.i386.rpm

libevent

openssl-devel

bzip2-devel

libcurl-devel

檢視此些包可以到網站rpmfind.net

下載下傳完成後安裝

安裝php

# tar -xf php-5.4.13.tar.bz2

# cd php-5.4.13

# ./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 --with-libevent-dir=/usr/local/libevent/

(此為一行指令)

# cd /usr/local/php/etc

# cp php-fpm.conf.default php-fpm.conf

# vim php-fpm.conf (修改值)

pm.max_children = 150

pm.start_servers = 5

pm.min_spare_servers = 5

pm.max_spare_servers = 10

# cd /root/mysql-compile/php-5.4.13

# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm

# chmod +x /etc/init.d/php-fpm

# chkconfig --add php-fpm

# service php-fpm start

# netstat -tunlp  (檢視9000端口是否開啟)

2. 配置nginx調用php

# vim /etc/nginx/nginx.conf  

将如下的location前邊#号去掉

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;

        }

    # vim /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;

3. 配置php使用memcache

需要到官方站點 pecl PECL is a repository for PHP Extensions

pecl.php.net  下載下傳memcache

編譯和安裝memcache

# tar -xf memcache-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

安裝完成會有如下一條資訊,将其複制

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

# mkdir /etc/php.d

# vim /etc/php.d/memcache.ini

extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/memcache.so

上邊此行的目錄就是剛剛複制的那個目錄,後邊加了一個memcache.so

# service php-fpm restart

此時php便可使用memcache記憶體緩存

4. 測試memcache是否被php調用

vim /web/html/test.php

<?php

$mem = new Memcache;

$mem->connect("127.0.0.1", 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.";         

?>

通路此檔案

http://192.168.11.151/test.php

5.檢視memcached是否存儲了testkey

get testkey 檢視其是否有鍵值

6. nginx整合memcached

server {

        listen       80;

        server_name  www.mysky.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        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://172.16.0.1;

1. 配置php.ini

vim /etc/php.ini

session.save_handler = memcache

session.save_path = "tcp://192.168.11.151:11211?persistent=1&weight=1&timeout=1&ret

ry_interval=15"(一行指令)

2. 測試是否工作正常

建立php頁面setsess.php,為用戶端設定啟用session:

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:

$memcache_obj = new Memcache;

$memcache_obj->connect('172.16.200.11', 11211);

$mysess=session_id();

var_dump($memcache_obj->get($mysess));

$memcache_obj->close();

memadmin-master.zip

解壓将其放在nginx所定義的網站目錄裡即可通路

本文轉自Winthcloud部落格51CTO部落格,原文連結http://blog.51cto.com/winthcloud/1895481如需轉載請自行聯系原作者

Winthcloud