1. 程式人生 > >Java MemCached Window簡單實現

Java MemCached Window簡單實現

1、下載下面附件 memcached-1.2.1-win32.zip 和 memcached-release_1.6.zip 。解壓到指定目錄,cmd切換進解壓後的 memcached-1.2.1-win32 目錄,執行 memcached.exe -d install 和 memcached.exe -l 127.0.0.1 -m 32 -d start 命令。這裡只為memcached分配32M記憶體,此時在“服務”中可以看到 memcached Server這個服務。

2、建立Server端程式碼往 memcached 中存放數值

package com.neusoft;

import org.apache.log4j.BasicConfigurator;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class ServerTest {

	public static void main(String[] args) {
		BasicConfigurator.configure();
		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 = new MemCachedClient();
		for ( int i = 0; i < 10; i++ ) {
			memCachedClient.set( "biao.li" + i, i+" >>> Hello!" );
		}
	}
}

3、建立Client程式碼獲取memcached 中的數值

package com.neusoft;

import org.apache.log4j.BasicConfigurator;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class ClientTest {

	public static void main(String[] args) {
		BasicConfigurator.configure();
		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 = new MemCachedClient();
		for ( int i = 0; i < 10; i++ ) {
			Object obj = memCachedClient.get("biao.li" + i);
			System.out.println(obj);
		}
	}
	
}