1.memcached java client一個實現的下載地址 http://www.whalin.com/memcached/#download 2. 利用memcached java client 一個簡單的應用 java 代碼 package memcache; import java.util.Date; import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool; public class Test { /** * @param args */ protected static MemCachedClient mcc = new MemCachedClient(); static { String[] servers ={"124.42.60.19:12000"}; 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
3.注釋掉buildCache(); 十秒后運行,輸出值為 null |