`
lauy
  • 浏览: 436012 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

使用 memcache java 客户端示例

 
阅读更多

原文出处:http://blog.chenlb.com/2008/12/use-memcache-java-client-demo.html

memcache java 客户端 api。地址:http://www.danga.com/memcached/apis.bml ,有种客户端,我这使用 Dustin Sallings 版的(已经在 google code 了 http://code.google.com/p/spymemcached/)。

spymemcached 的下载地址:http://spymemcached.googlecode.com/files/memcached-2.2.jar 它依赖 spy.jar,spy.jar的下载地址:http://bleu.west.spy.net/~dustin/repo/spy/jars/spy-2.4.jar

把两个jar放到classpath下,然后写代码试用下:写入

 
  1. package com.chenlb.use;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.Serializable;  
  5. import java.net.InetSocketAddress;  
  6. import java.util.Date;  
  7.   
  8. import net.spy.memcached.MemcachedClient;  
  9.   
  10. public class MemcacheUse {  
  11.   
  12.     private static class MyData implements Serializable {  
  13.         private static final long serialVersionUID = 1L;  
  14.         private long d = new Date().getTime();  
  15.         public String toString() {  
  16.             return "my data ["+d+"]";  
  17.         }  
  18.     }  
  19.   
  20.     public static void main(String[] args) throws IOException {  
  21.         MyData myData = new MyData();  
  22.   
  23.         MemcachedClient c=new MemcachedClient(new InetSocketAddress("localhost"11211));  
  24.         // Store a value (async) for one hour  
  25.   
  26.         c.set("someKey"3600, myData);  
  27.   
  28.         // Retrieve a value (synchronously).  
  29.         Object myObject=c.get("someKey");  
  30.   
  31.         c.shutdown();  
  32.   
  33.         System.out.println(myObject);  
  34.   
  35.     }  
  36.   
  37. }  

读:主要是验证下,一小时后读是否有效。

 
  1. package com.chenlb.use;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5.   
  6. import net.spy.memcached.MemcachedClient;  
  7.   
  8. public class MemcacheGetUse {  
  9.   
  10.     public static void main(String[] args) throws IOException {  
  11.         MemcachedClient c=new MemcachedClient(new InetSocketAddress("172.16.249.220"11211));  
  12.   
  13.         // Retrieve a value (synchronously).  
  14.         Object myObject=c.get("someKey");  
  15.   
  16.         System.out.println(myObject);  
  17.   
  18.         c.shutdown();  
  19.     }  
  20.   
  21. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics