转载自 http://oursimplehouse.blog.sohu.com/63588732.html
安装 memcached:
1、下载memcached-1.2.2.tar.gz
2、tar xvzf memcached-1.2.2.tar.gz
3、./configure;make;make install
安装python API组件:
1、下载python-memcached-1.39.tar.gz
2、tar xvzf python-memcached-1.39.tar.gz
3、python setup.py install
启动memcached
memcached -d -m 64 -l 10.1.41.113 -p 11211
启动的这个memcached为一个后台守护进程模式(-d), 然后缓存的空间为64M(-m), 监听(-l)服务器10.1.41.113的11212号端口(-p)
root下要加-u 指定user参数
memcached -u bj1822 -d -m 64 -l 10.1.41.113 -p 11211
memcached -h
memcached 1.2.2
-p <num> TCP port number to listen on (default: 11211)
-U <num> UDP port number to listen on (default: 0, off)
-s <file> unix socket path to listen on (disables network support)
-l <ip_addr> interface to listen on, default is INDRR_ANY
-d run as a daemon
-r maximize core file limit
-u <username> assume identity of <username> (only when run as root)
-m <num> max memory to use for items in megabytes, default is 64 MB
-M return error on memory exhausted (rather than removing items)
-c <num> max simultaneous connections, default is 1024
-k lock down all paged memory
-v verbose (print errors/warnings while in event loop)
-vv very verbose (also print client commands/reponses)
-h print this help and exit
-i print memcached and libevent license
-b run a managed instanced (mnemonic: buckets)
-P <file> save PID in <file>, only used with -d option
-f <factor> chunk size growth factor, default 1.25
-n <bytes> minimum space allocated for key+value+flags, default 48
编写python程序:
import memcache, time
mc = memcache.Client([‘10.1.41.113:11211‘], debug=0)
连接到10.1.41.113的11211端口,也就是memcachd启动的端口。
mc.set("some_key", "Some value")
设置key和value,第三个参数默认为0,也就是数据永不超时。
如果这样设置:
mc.set("some_key", "Some value",1)
表示一秒后超时
过两秒打印value的话
time.sleep ( 2)
value = mc.get("some_key")
print value
结果就是None了。
删除
mc.set("another_key",
3)
mc.delete("another_key")
自增和自减
mc.set("key",
"1")
mc.incr("key")
mc.decr("key")
关于LRU
LRU是缓冲超过存储上限时删掉队尾也就是最长时间没人访问的元素,参数是-M。但设置了-M和过期时效会存在将未失效的元素删去的风险。所以网上有人改了下代码,增加对过期时效的判断:
返回超时时间的代码:
if (exptime > REALTIME_MAXDELTA)
return (rel_time_t) (exptime - stats.started);
else {
return (rel_time_t) (exptime + current_time);
}
memcached的失效时间格式有两种,当大于60*60*24*30也就是30天的秒数时就是过期距1970年1月1日零时的秒数,否则是有效的秒数。
删除cache的代码:
for (search = tails[id]; tries>0 && search; tries--, search=search->prev) {
if (search->refcount==0) {
item_unlink(search);
break;
}
}
增加条件:
search->exptime && search->exptime <= current_time
这样就可以保证删除的都是过期了的元素了。