memcached之java客户端:spymemcached使用

来源:互联网 发布:thttpd Windows 编辑:程序博客网 时间:2024/05/16 14:30
memcached之java客户端:spymemcached使用
---------

一个简单的示例:

[java] view plaincopy
  1. MemcachedClient c = new MemcachedClient(new InetSocketAddress("hostname",portNum));  
  2. //异步方式存储一个值一个小时  
  3. c.set("someKey",3600,someObject);  
  4. //同步方式获取一个值  
  5. Object myObject = c.get("someKey");  


利用异步获取的优势
MemcachedClient可以异步处理消息,如果一个memcached服务器不能连接,如例,MemcachedConnection将继续尝试重新连接。为了防止造成你的应用程序挂起,可以使用异步机制,异步获取数据并对超时的请求取消对服务器的操作。
[java] view plaincopy
  1. //获取一个连接到几个服务端的memcached的客户端  
  2. MemcachedClient c = new MemcachedClient(AddrUtil.getAddresses("server1:11211 server2:11211"));  
  3. //获取值,如果在5秒内没有返回值,将取消  
  4. Object myObj = null;  
  5. Future<Object> f = c.asyncGet("someKey");  
  6. try{  
  7.     myObj = f.get(5,TimeUnit.SECONDS);  
  8. }catch(TimeoutException e){  
  9.     f.cancel(false);  
  10. }  


建立连接
1.建立一个二进制协议连接
如例:
[java] view plaincopy
  1. //获取一个通过二进制协议连接到几个服务端的memcached的客户端  
  2. MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(),  
  3.     AddrUtil.getAddresses("server1:11212 server2:11212"));  
  4. ......  
2.建立一个二进制协议的SASL连接

[java] view plaincopy
  1. //创建一个AuthDescriptor,这是一个PLAIN的SASL,因此用户名与密码仅仅是字符串  
  2. MemcachedClient mc = null;  
  3. AuthDescriptor ad = new AuthDescriptor(new String[]{"PLAIN"},  
  4.     new PlainCallbackHandler(username,password));  
  5. //然后连接使用ConnectionFactoryBuilder,二进制是必须的  
  6. try{  
  7.     if(mc == null){  
  8.         mc = new MemcachedClient(new ConnectionFactoryBuilder()  
  9.             .setProtocol(Protocol.BINARY)  
  10.             .setAuthDescriptor(ad).build(),  
  11.             AddrUtil.getAddresses(host));  
  12.     }  
  13. }catch(IOException ex){  
  14.     System.err.println("Couldn't create a connection,bailing out:\nIOException"  
  15.     +ex.getMessage());  
  16. }  
3.建立Membase连接(Membase是nosql数据库)

[java] view plaincopy
  1. MemcachedClient mc;  
  2. try{  
  3.     URI base = new URI("http://localhost:8091/pools");  
  4.     ArrayList baseURIs = new ArrayList();  
  5.     baseURIs.add(base);  
  6.     mc = new MemcachedClient(baseURIs,"bucket_name","bucket_password");  
  7.     ...  
  8. }catch(IOException ex){  
  9.     Logger.getLogger(Main.class.getName).log(Level.SEVERE,null,ex);  
  10. }catch(ConfigurationException ex){  
  11.     Logger.getLogger(Main.class.getName).log(Level.SEVERE,null,ex);  
  12. }catch(URISyntaxException ex){  
  13.     Logger.getLogger(Main.class.getName).log(Level.SEVERE,null,ex);  
  14. }  
  15. mc.set("hello",0,"world");  
  16. String result = (String)mc.get("hello");  
  17. assert(result.equals("world"));  
  18. mc.shutdown(3,TimeUnit.SECONDS);  
原创粉丝点击