簡介git
Memcached是一個高性能的分佈式內存對象緩存系統,用於動態Web應用以減輕數據庫負載。它經過在內存中緩存數據和對象減小讀取數據庫的次數,從而提升動態、數據庫驅動網站的速度。Memcached基於一個存儲鍵/值的hashmap。其守護進程(daemon)是用C語言寫的,可是客戶端能夠用任何語言來編寫,並經過memcached協議與守護進程通訊。github
安裝memecache數據庫
cd /usr/local/src wget http://memcached.org/latest tar -zxvf memcached-1.x.x.tar.gz cd memcached-1.x.x ./configure –prefix=/usr/local/memcached&& make && make test && make install
報錯處理:找不到libevent
緩存
wget https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz tar zxvf libevent-2.1.8-stable.tar.gz -C /usr/local/src/ cd /usr/local/src/ ./configure --prefix=/usr/local/ make && make install 編譯時指定libevent ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local/ 或yum install –y libevent*
啓動memcache
memcached -d -m 10 -u root -l 192.168.100.83 -p 12000 -c 256 -P /export/servers/memcache/logs/memcache.pid
-p 指定端口號(默認11211)
-m 指定最大使用內存大小(默認64MB)
-t 線程數(默認4)
-l 鏈接的IP地址, 默認是本機
-d 之後臺守護進程的方式啓動
-c 最大同時鏈接數,默認是1024
-P 制定memecache的pid文件
-h 打印幫助信息
檢查memcache是否啓動
app
Memcache經常使用命令
存儲命令: set/add/replace/append/prepend/cas
獲取命令: get/gets
其餘命令: delete/stats.分佈式
import memcache mc=memcache.Client([("192.168.100.83:12000",1),("192.168.100.83:12001",2)],debug=True) mc.set("k1","v1") print (mc.get("k1"))
import memcache mc=memcache.Client(["192.168.100.83:12001"],debug=True) mc.add("k1","v1") #add(key,value) print (mc.get("k1")) # print (dir(mc)) #replace mc.replace("k1",'hello world') print mc.get("k1") #set(key,value) mc.set("k2","v2") print mc.get("k2") mc.set("k2","hello2") print mc.get("k2") # set和add的區別 #set = add + replace # 若是這個key值存在,add就會報錯,set不會報錯,set會進行從新賦值並覆蓋 # set_multi(dict) 一次設置多個key:value # get_multi(list) 一次獲取到多個key,每一個key要以list的形式做爲參數傳入 返回類型爲dict # get(key) 得到該key對應的value值 # mc.set_multi({"k100":"v100","k101":"v101","k102":"v102"}) # print mc.get_multi(["k100","k101"]) mc.set_multi({"test1":"v100","test2":"v101","test3":"v102"}) print mc.get_multi(['test1']) mc.delete('test1') mc.delete_multi(['test2','test3']) print mc.get_multi(["test1","test2","test3"]) mc.set_multi({"test1":"v100","test2":"v101","test3":"v102"}) mc.append("test1","ling") #在後面追加值 print mc.get("test1") mc.prepend("test2","hello") #在前面加入值 print mc.get("test2") # incr 和 decr # incr 默認自增1 第二個參數爲自增的步長n # decr 默認自減1 第二個參數爲自減的步長n mc.set("shop",1000) #自增初始值1000,默認自增1 mc.incr("shop") print mc.get("shop") mc.incr("shop",100) #自增步長爲100 print mc.get("shop") mc.decr("shop") #自減 print mc.get("shop") mc.decr("shop",500) #自減步長爲500 print mc.get("shop")