memcache是一套分佈式的高速緩存系統,由LiveJournal的Brad Fitzpatrick開發,但目前被許多網站使用以提升網站的訪問速度,尤其對於一些大型的、需要頻繁訪問數據庫的網站訪問速度提升效果十分顯著[1] 。這是一套開放源代碼軟件,以BSD license授權發佈。
在 Memcached中可以保存的item數據量是沒有限制的,只要內存足夠 。
memcached是鍵值一一對應,key默認最大不能超過128個字 節,value默認大小是1M,也就是一個slabs,如果要存2M的值(連續的),不能用兩個slabs,因爲兩個slabs不是連續的,無法在內存中
存儲,故需要修改slabs的大小,多個key和value進行存儲時,即使這個slabs沒有利用完,那麼也不會存放別的數據。
下面是一個完整的java的memcached的例子。
package com.dert.memcache;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MemcacheTest {
/**
* @param args
*/
public static void main(String[] args) {
/**
* 初始化SockIOPool,管理memcached的連接池
* */
String[] servers = { "127.0.0.1:11211" };
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(servers);
pool.setFailover(true);
pool.setInitConn(10);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaintSleep(30);
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setAliveCheck(true);
pool.initialize();
/**
* 建立MemcachedClient實例
* */
MemCachedClient memCachedClient = new MemCachedClient();
System.out.println("memCacheClient");
for (int i = 0; i < 1000; i++) {
/**
* 將對象加入到memcached緩存
* */
boolean success = memCachedClient.set("" + i, "Hello!");
System.out.println("memCacheClient");
/**
* 從memcached緩存中按key值取對象
* */
String result = (String) memCachedClient.get("" + i);
System.out.println(String.format("set( %d ): %s", i, success));
System.out.println(String.format("get( %d ): %s", i, result));
}
}
}
首先,我們需要在windows上面正確安裝上面memcached服務器程序,並且啓動服務器,
然後下載memcached的jar包,一共有4個,然後上面的程序就能正確運行。
正確的結果,都是true,如果不對,那就會打印出false。