首页 > 代码库 > net spy memcached 使用demo

net spy memcached 使用demo

package memcached;

import java.io.IOException;
import java.net.InetSocketAddress;

import net.spy.memcached.MemcachedClient;

public class Client {

	private final int expiredSeconds = 100;

	private final InetSocketAddress server = new InetSocketAddress("127.0.0.1",
			10101);

	private MemcachedClient memcachedClient;

	public void init() {
		try {
			memcachedClient = new MemcachedClient(server);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void put(String key, Object obj) {
		memcachedClient.set(key, expiredSeconds, obj);
	}

	public void delete(String key) {
		memcachedClient.delete(key);
	}

	public Object get(String key) {
		return memcachedClient.get(key);
	}

	public static void main(String args[]) {
		Client c = new Client();
		c.init();
		long begin = System.currentTimeMillis();
		for(int i=0;i<100;i++) {
			c.put(i+"", i);
			System.out.println(c.get(i+""));
		}
		System.out.println((System.currentTimeMillis()-begin)+"ms");
	}
	
}
第一是设置过期时间,单位为秒,这里注意在put的时候,该值作为set的一个参数,但是如果该值大于30天的秒数的话,就会当成是unix时间来设置过期时间而不是offset。
第二行是本地的一个memcached的server地址和端口,调用MemcacedClient实例化一个MemcachedClient对象,下面就自定义put,get,delete常用方法就可以了
直接结果如下:
2014-08-22 09:35:01.891 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=/127.0.0.1:10101, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue2014-08-22 09:35:01.902 WARN net.spy.memcached.MemcachedConnection:  Could not redistribute to another node, retrying primary node for 0.2014-08-22 09:35:01.904 WARN net.spy.memcached.MemcachedConnection:  Could not redistribute to another node, retrying primary node for 0.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989992ms