步驟如下:
1.下載memcached for Win32:
http://jehiah.cz/projects/memcached-win32/
安裝啟動並執行方法:
http://www.ccvita.com/258.html
2.下載memcache的Java支援包
http://www.whalin.com/memcached/#download
3.代碼
- package demo;
- import java.util.Date;
- import com.danga.MemCached.MemCachedClient;
- import com.danga.MemCached.SockIOPool;
- public class Test {
- protected static MemCachedClient mcc = new MemCachedClient();
-
- static {
- String[] servers ={"127.0.0.1:11211"};
-
- Integer[] weights = { 3 };
-
- //建立一個執行個體對象SockIOPool
- SockIOPool pool = SockIOPool.getInstance();
-
- // set the servers and the weights
- //設定Memcached Server
- pool.setServers( servers );
- pool.setWeights( weights );
-
- // set some basic pool settings
- // 5 initial, 5 min, and 250 max conns
- // and set the max idle time for a conn
- // to 6 hours
- pool.setInitConn( 5 );
- pool.setMinConn( 5 );
- pool.setMaxConn( 250 );
- pool.setMaxIdle( 1000 * 60 * 60 * 6 );
-
- // set the sleep for the maint thread
- // it will wake up every x seconds and
- // maintain the pool size
- pool.setMaintSleep( 30 );
-
- // Tcp的規則就是在發送一個包之前,本地機器會等待遠程主機
- // 對上一次發送的包的確認資訊到來;這個方法就可以關閉通訊端的緩衝,
- // 以至這個包準備好了就發;
- pool.setNagle( false );
- //串連建立後對逾時的控制
- pool.setSocketTO( 3000 );
- //串連建立時對逾時的控制
- pool.setSocketConnectTO( 0 );
-
- // initialize the connection pool
- //初始化一些值並與MemcachedServer段建立串連
- pool.initialize();
-
-
- // lets set some compression on for the client
- // compress anything larger than 64k
- mcc.setCompressEnable( true );
- mcc.setCompressThreshold( 64 * 1024 );
- }
-
- public static void bulidCache(){
- //set(key,value,Date) ,Date是一個到期時間,如果想讓這個到期時間生效的話,這裡傳遞的new Date(long date) 中參數date,需要是個大於或等於1000的值。
- //因為java client的實現源碼裡是這樣實現的 expiry.getTime() / 1000 ,也就是說,如果 小於1000的值,除以1000以後都是0,即永不到期
- mcc.set( "test", "This is a test String" ,new Date(10000)); //十秒後到期
-
- }
-
- public static void output() {
- //從cache裡取值
- String value = (String) mcc.get( "test" );
- System.out.println(value);
- }
-
- public static void main(String[] args){
- bulidCache();
- output();
- }
- }
運行:
運行輸出值為:This is a test String
注釋掉buildCache();
十秒後運行,輸出值為 null
注意:
1.程式需要log4j.jar
2.memcache預設連接埠:11211
其他資源:
http://www.javayou.com/diary/7141
http://www.javaeye.com/topic/61898
本文參考自:http://ttitfly.javaeye.com/blog/110495