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地址和port,调用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 queue 2014-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. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 92ms