---------
一個簡單的示例:
- 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("someKey");
- try{
- myObj = f.get(5,TimeUnit.SECONDS);
- }catch(TimeoutException e){
- f.cancel(false);
- }
1.建立一個二進制協議連接
如例:
- //獲取一個通過二進制協議連接到幾個服務端的memcached的客戶端
- MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(),
- AddrUtil.getAddresses("server1:11212 server2:11212"));
- ......
- //創建一個AuthDescriptor,這是一個PLAIN的SASL,因此用戶名與密碼僅僅是字符串
- MemcachedClient mc = null;
- AuthDescriptor ad = new AuthDescriptor(new String[]{"PLAIN"},
- 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("Couldn't create a connection,bailing out:\nIOException"
- +ex.getMessage());
- }
- MemcachedClient mc;
- try{
- URI base = new URI("http://localhost:8091/pools");
- ArrayList baseURIs = new ArrayList();
- baseURIs.add(base);
- mc = new MemcachedClient(baseURIs,"bucket_name","bucket_password");
- ...
- }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("hello",0,"world");
- String result = (String)mc.get("hello");
- assert(result.equals("world"));
- mc.shutdown(3,TimeUnit.SECONDS);