天堂1111 发表于 2015-11-18 14:54:33

memcached之java客户端:spymemcached使用

memcached之java客户端:spymemcached使用

---------
  一个简单的示例:
  

MemcachedClient c = new MemcachedClient(new InetSocketAddress("hostname",portNum));
//异步方式存储一个值一个小时
c.set("someKey",3600,someObject);
//同步方式获取一个值
Object myObject = c.get("someKey");
  



利用异步获取的优势

MemcachedClient可以异步处理消息,如果一个memcached服务器不能连接,如例,MemcachedConnection将继续尝试重新连接。为了防止造成你的应用程序挂起,可以使用异步机制,异步获取数据并对超时的请求取消对服务器的操作。

//获取一个连接到几个服务端的memcached的客户端
MemcachedClient c = new MemcachedClient(AddrUtil.getAddresses("server1:11211 server2:11211"));
//获取值,如果在5秒内没有返回值,将取消
Object myObj = null;
Future<Object> f = c.asyncGet(&quot;someKey&quot;);
try{
myObj = f.get(5,TimeUnit.SECONDS);
}catch(TimeoutException e){
f.cancel(false);
}
  



建立连接

1.建立一个二进制协议连接

如例:

//获取一个通过二进制协议连接到几个服务端的memcached的客户端
MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(),
AddrUtil.getAddresses(&quot;server1:11212 server2:11212&quot;));
......2.建立一个二进制协议的SASL连接  

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

MemcachedClient mc;
try{
URI base = new URI(&quot;http://localhost:8091/pools&quot;);
ArrayList baseURIs = new ArrayList();
baseURIs.add(base);
mc = new MemcachedClient(baseURIs,&quot;bucket_name&quot;,&quot;bucket_password&quot;);
...
}catch(IOException ex){
Logger.getLogger(Main.class.getName).log(Level.SEVERE,null,ex);
}catch(ConfigurationException ex){
Logger.getLogger(Main.class.getName).log(Level.SEVERE,null,ex);
}catch(URISyntaxException ex){
Logger.getLogger(Main.class.getName).log(Level.SEVERE,null,ex);
}
mc.set(&quot;hello&quot;,0,&quot;world&quot;);
String result = (String)mc.get(&quot;hello&quot;);
assert(result.equals(&quot;world&quot;));
mc.shutdown(3,TimeUnit.SECONDS);
  

版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: memcached之java客户端:spymemcached使用