一. memcached簡介
memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
(由 LiveJournal旗下的Danga Interactive研發)
#高性能,分布式緩存系統
緩存服務器:
緩存:cache,無持久存儲功能;
bypass緩存 # 旁掛式緩存
k/v cache,僅支持存儲流式化數據;
特性:
k/v cache:僅可序列化數據;存儲項:k/v (key:value)
智能性一半依賴于客戶端(調用memcached的API開發程序),一半依賴于服務端;
分布式緩存:互不通信的分布式集群;
分布式系統請求路由方法:取模法(對機器數量取模來決定發往哪臺機器),
一致性哈希算法(順時針哈希環);
算法復雜度:O(1)
清理過期緩存項:
緩存耗盡:LRU
緩存項過期:惰性清理機制
#即會定期檢查緩存,當緩存失效時候并不做清理,而是有新緩存寫入時
候,直接覆蓋原有的舊緩存內容
二. 安裝配置:
由CentOS 7 base倉庫直接提供:
監聽的端口:
11211/tcp, 11211/udp
主程序:/usr/bin/memcached
配置文件:/etc/sysconfig/memcached
Unit File:memcached.service
管理工具:memcached-tool
協議格式:memcached協議
文本格式
二進制格式
三.memcache 命令詳解
詳細協議幫助 : /usr/share/doc/memcached-1.4.15/protocol.txt
命令:
統計類:stats, stats items, stats slabs, stats sizes
存儲類:set, add, replace, append, prepend
命令格式:<command name> <key> <flags> <exptime> <bytes>
額外信息 過期時間 大小
<cas unique> #回車后才能輸入值
key key 用于查找緩存值
flags 可以包括鍵值對的整型參數,客戶機使用它存儲關于鍵值對的額外信息
# 默認用1 即可
expiration time 在緩存中保存鍵值對的時間長度(以秒為單位,0 表示永
遠)
bytes 在緩存中存儲的字節點
value 存儲的值(始終位于第二行)
檢索類:get, delete, incr/decr
清空:flush_all
示例:
telnet> add KEY <flags> <expiretime> <bytes> \r
telnet> VALUE參數 用法
memcached程序的常用選項:
-m <num>:Use <num> MB memory max to use for object storage; the
default is 64 megabytes.
-c <num>:Use <num> max simultaneous connections; the default is 1024.
-u <username>:以指定的用戶身份來運行進程;
-l <ip_addr>:監聽的IP地址,默認為本機所有地址;
-p <num>:監聽的TCP端口, the default is port 11211.
-U <num>:Listen on UDP port <num>, the default is port 11211, 0 is off.
-M:內存耗盡時,不執行LRU清理緩存,而是拒絕存入新的緩存項,直到有多余的空
間可用時為止;
-f <factor>:增長因子(內存分塊的大小增長倍數);默認是1.25;
-t <threads>:啟動的用于響應用戶請求的線程數;
memcached默認沒有認證機制,可借用于SASL進行認證;
SASL:Simple Authentication Secure Layer
三. API:
php-pecl-memcache
php-pecl-memcached
python-memcached
libmemcached
#此工具包中包含多個memcache的命令行管理工具
libmemcached-devel
命令行工具:
memcached-tool SERVER:PORT COMMAND
————————————————-
[root@localhost ~]# rpm -ql libmemcached
/usr/bin/memaslap
/usr/bin/memcapable
/usr/bin/memcat
/usr/bin/memcp
/usr/bin/memdump
/usr/bin/memerror
/usr/bin/memexist
/usr/bin/memflush
/usr/bin/memparse
/usr/bin/memping
/usr/bin/memrm
/usr/bin/memslap
/usr/bin/memstat
/usr/bin/memtouch
————————————————–
四. 利用 telnet 管理memcache 示例
1. yum install telnet
–> telnet localhost 11211
stats:
五. nginx 對memcache 的支持
所需模塊: ngx_http_memcached_module
Syntax: memcached_bind address [transparent] | off;
Default: —
Context: http, server, location
#用于綁定 memcache 服務器
Syntax: memcached_pass address;
Default: —
Context: location, if in location
#綁定memcache 集群
eg:
server {
location / {
set $memcached_key "$uri?$args";
#將指定的key 放入memcache 生成緩存;
memcached_pass host:11211;
error_page 404 502 504 = @fallback;
}
location @fallback {
proxy_pass http://backend;
}
}
============================================================
原創文章,作者:ldt195175108,如若轉載,請注明出處:http://www.www58058.com/55611