memcached:緩存服務器,但本身無法決定緩存任何數據
一半依賴客戶端,一半依賴於服務器
set key 5 60 hello
清理機制:lazy:惰性, LRU,最近最少使用
內存緩存服務器
最小48bytes
最大1M
buddy system:夥伴系統
避免內存外碎片,內存頁面和頁面之間的碎片
slab allocator:slab 分離器
避免內存內碎片,專門事先爲每一種數據結構把幾個內存頁面分成n個小的頁面來存儲小的數據。
memcached:不通信分佈式緩存服務器
http://www.memcached.org/
event-libevent 提供事件驅動
[root@localhost memcached-1.4.35]# yum -y install cyrus-sasl-devel
[root@localhost ~]# tar -xf libevent-2.0.20-stable.tar.gz
[root@localhost libevent-2.0.20-stable]# ./configure --prefix=/usr/local/libevent
[root@localhost libevent-2.0.20-stable]# make && make install
[root@localhost ~]# tar -xf memcached-1.4.35.tar.gz
[root@localhost memcached-1.4.35]# yum -y install cyrus-sasl-devel.i686
[root@localhost memcached-1.4.35]# ./configure --enable-sasl --prefix=/usr/local/memcached --with-libevent=/usr/local/libevent
[root@localhost libevent-2.0.20-stable]# make && make install
[root@localhost ~]# /usr/local/memcached/bin/memcached -h
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進行用戶認證;
[root@localhost ~]# /usr/local/memcached/bin/memcached -m 128 -n 20 -f 1.25 -vv -u nobody -d
指定最大內存空間128M, 指定最小的slab chunk爲20字節,指定增長因子爲1.25 -d後臺運行
slab class 1: chunk size 72 perslab 14563
第一次爲72字節 一共有14563個
[root@localhost ~]# netstat -tnulp |grep mem
tcp 0 0 0.0.0.0:11211 0.0.0.0:* LISTEN 1628/memcached
tcp 0 0 :::11211 :::* LISTEN 1628/memcached
udp 0 0 0.0.0.0:11211 0.0.0.0:* 1628/memcached
udp 0 0 :::11211 :::* 1628/memcached
[root@localhost ~]# yum -y install telnet
[root@localhost ~]# telnet localhost 11211
<36 stats 顯示當前狀態
STAT get_hits 0 get命中率
STAT get_misses 0 get未命中率
add命令:添加一個新鍵
add keyname flag() timeout(超時時間) datasize(數據大小)
如:
add mykey 1 10 12
hello world!
---------------------
add mykey 0 60 5
<36 add mykey 0 60 5
hello
>36 STORED
STORED
get mykey
<36 get mykey
>36 sending key mykey
>36 END
VALUE mykey 0 5
hello
END
---------------------
get命令:
get keyname
如: get mykey
VALUE mykey 0 12
Hello world!
END
基本命令
get 讀取一個鍵 get mykey
set 設定一個鍵 set mykey 0 60 5
add 創建一個鍵 add newkey 0 60 5
replace 替換一個現有鍵的值 replace key 0 60 5
append 在一個鍵後面新增一個值 append key 0 60 15
prepend 在已存在的鍵的前面新增一個值 prepend 0 60 15
incr 讓某些值自動+1,相當於I++ incr mykey 2
decr 讓某些值自動-1,相當於I-- decr mykey 5
delete 刪除某個鍵 delete mykey
flush_all 清除所有鍵 flush_all
flush_all900
stats 顯示狀態,可以只顯示某一個狀態
stats
stats slabs
stats malloc
stats items
stats detail
stats sizes
stats reset
version 顯示版本
verbosity 提升日誌級別
quit 退出
查看信息中的關鍵字中英文對照表
pid memcache服務器的進程ID
uptime 服務器已經運行的秒數
time 服務器當前的unix時間戳
version memcache版本
pointer_size 當前操作系統的指針大小(32位系統一般是32bit)
rusage_user 進程的累積用戶時間
rusage_system 進程的累積系統時間
curr_items 服務器當前存儲的item數量
total_items 從服務器啓動以後存儲的items總量
bytes 當前服務器存儲items佔用的字節數
curr_connections 當前打開着的連接數
total_connections 從服務器啓動以後曾經打開過的連接數
cmd_get get命令(獲取)總請求次數
cmd_set set命令(保存)總請求次數
get_hits 總命中次數
get_misses 總未命中次數
evictions 爲獲取空閒內存而刪除的items數(分配給mamcache)的空間用滿意後需要刪除舊的items來得到空間分配給新的items
limit_maxbytes 分配給memcache的內存大小(字節)
threads當前線程數
memcached SysV的startup腳本代碼如下所示,將其建立爲/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=""
##用於判斷腳本的配置文件。
[ -f /etc/sysconfig/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
----------------------------------------
[root@localhost ~]# chmod +x /etc/init.d/memcached
[root@localhost ~]# chkconfig --add memcached
[root@localhost ~]# chkconfig memcached on
[root@localhost ~]#
[root@localhost ~]# chkconfig list |grep mem
[root@localhost ~]# chkconfig --list |grep mem
memcached 0:off1:off2:on3:on4:on5:on6:off
[root@localhost ~]# service memcached start
Starting Distributed memory caching (memcached): [ OK ]
/etc/init.d/memcached: line 84: exit: 0#!/bin/bash: numeric argument required
[root@localhost ~]#
給腳本提供配置文件
[root@localhost sysconfig]# vim /etc/sysconfig/memcached
PORT="11211"
USER="nobody"
MAXCONN="1024"
CACHESIZE="180"
OPTIONS=""
----------------
[root@localhost sysconfig]# service memcached restart
[root@localhost sysconfig]# telnet localhost 11211
stats
STAT limit_maxbytes 188743680
-------------------------------------------
安裝Memcache的PHP擴展
location / {
root /web/htdocs;
index index.php index.html;
}
nginx開啓php功能
location ~ \.php$ {
root /web/htdocs;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
[root@localhost nginx]# service nginx reload
[root@localhost nginx]# vim /web/htdocs/index.php
<h1>Test Page </h1>
<?php
phpinfo();
?>
①安裝PHP的memcache擴展
# tar xf memcache-2.2.6.tgz
# cd memcache-2.2.6
[root@localhost memcache-2.2.6]# /usr/local/php/bin/phpize
# ./configure --with-php-config=/usr/local/php/bin/php-config --enable-memcache
# make && make install
上述安裝完後會有類似以下的提示:
Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/
[root@localhost memcache-2.2.6]# mkdir /etc/php.d
[root@localhost memcache-2.2.6]# vim /etc/php.d/memcache.ini
extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/memcache.so
對memcached功能進行測試,在網站目錄中建立測試頁面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.3.239/test.php
如果有輸出“Hello World is from memcached.”等信息,則表明memcache已經能夠正常工作。
[root@localhost memcached-1.4.35]# telnet localhost 11211
Trying ::1...
Connected to localhost.
Escape character is '^]'.
get testkey
VALUE testkey 0 11
Hello World
END
使用libmemcached的客戶端工具:
訪問memcached的傳統方法是使用基於perl語言開發的Cache::memcached模塊,這個模塊在大多數perl代碼中都能良好的工作,但也有着衆所周知的性能方面的問題。libMemcached則是基於C語言開發的開源的C/C++代碼訪問memcached的庫文件,同時,它還提供了數個可以遠程使用的memcached管理工具,如memcat, memping,memstat,memslap等。
1) 編譯安裝libmemcached
# tar xf libmemcached-1.0.2.tar.gz
# cd libmemcached-1.0.2
# ./configure
# make && make install
# ldconfig
2) 客戶端工具
# memcat --servers=127.0.0.1:11211 mykey
# memping
# memslap
# memstat
Nginx整合memcached:
server {
listen 80;
server_name www.mylinux.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; ##後端服務器
}
}
LVS Web php session memcached
前提:
1、配置各php支持使用memcache;
2、安裝配置好memcached服務器,這裏假設其地址爲172.16.200.11,端口爲11211;
一、配置php將會話保存至memcached中
編輯php.ini文件,確保如下兩個參數的值分別如下所示:
[root@localhost ~]# vim /etc/php.ini
session.save_handler = memcache
session.save_path = "tcp://172.16.200.11:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
[root@localhost ~]# service php-fpm restart
二、測試
新建php頁面setsess.php,爲客戶端設置啓用session:
[root@localhost ~]# vim /usr/html/setsees.php
<?php
session_start();
if (!isset($_SESSION['mylinux.com'])) {
$_SESSION['www.mylinux.com'] = time();
}
print $_SESSION['www.mylinux.com'];
print "<br><br>";
print "Session ID: " . session_id();
?>
新建php頁面showsess.php,獲取當前用戶的會話ID:
[root@localhost ~]# vim /usr/html/showsess.php
<?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();
?>
<?php
// Generating cookies must take place before any HTML.
// Check for existing "SessionId" cookie
$session = $HTTP_COOKIE_VARS["SessionId"];
if ( $session == "" ) {
// Generate time-based unique id.
// Use user's IP address to make more unique.
$session = uniqid ( getenv ( "REMOTE_ADDR" ) );
// Send session id - expires when browser exits
SetCookie ( "SessionId", $session );
}
?>
<HTML>
<HEAD><TITLE>Session Test</TITLE></HEAD>
<BODY> <br> 16 Current session id: <?php echo $session ?>
</BODY></HTML>
memadmin-master 的安裝
[root@localhost ~]# mv memadmin-master /usr/html/mmaster
[root@localhost mmaster]# vim config.php #可以修改memadmin的登錄密碼
http://192.168.3.239/mmaster