菜鸟学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 安装与配置


准备工作 下载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

add firstkey 0 20 5

hello


get firstkey

(此时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=$?

       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


添加可执行



配置php调用memcached


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/

(此为一行命令)

# make && make install

# 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

# make && make install

安装完成会有如下一条信息,将其复制

/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

# telnet localhost 11211

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;

       }

}





配置php将会话保存至memcached中


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"(一行命令)

# service php-fpm restart


2. 测试是否工作正常

新建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();

?>




图形化的memcached监控和管理工具

memadmin-master.zip


解压将其放在nginx所定义的网站目录里即可访问