论坛首页 Java企业应用论坛

xmemecached连接memcached服务器

浏览 1893 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-04-24   最后修改:2012-04-24
1. 去http://code.google.com/p/xmemcached/downloads/list网站下载最新的xmemcached版本
2. 去http://www.slf4j.org/download.html下载最新的sfl4包
3.将xmemcached-x.x.x.jar和slf4j-api-x.x.x.jar和slf4j-simple-x.x.x.jar文件拷入工程下
4.启动装有memcached的服务器
5.用如下程序测试:
public class MemcachedTest {

	public static void main(String[] args) {
		
		//192.168.0.69为memcached服务器的IP
        MemcachedClientBuilder builder = 
        	new XMemcachedClientBuilder(AddrUtil.getAddresses("192.168.0.69:1200"));
        try {
			MemcachedClient client = builder.build();
			client.set("hello", 0, "Hello world1");
			
			System.out.println("hello1=" + client.get("hello"));
			
			//获取cas值
			GetsResponse<String> result = client.gets("hello");
			long cas = result.getCas();
			System.out.println("cas=" + cas);
			
			//重新设置hello的值
			client.set("hello", 0, "Hello world2");
			
			//方法一:更新hello的值
			if(client.cas("hello", 0, "New hello world", cas))
			{
				System.out.println("Update hello successfully!");
			}
			else
			{
				System.out.println("Update hello error!");
			}
			System.out.println("hello2=" + client.get("hello"));
			
			//方法二:更新hello的值
			client.cas("hello", new CASOperation<String>(){
				public int getMaxTries() {
					return 1;
				}

				public String getNewValue(long currentCas, String currentValue) {
					return "Hello world3";
				}
			});
			System.out.println("hello3=" + client.get("hello"));
			
			//删除hello的值
			client.delete("hello");
			System.out.println("hello4=" + client.get("hello"));
			
			client.shutdown();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
	}
}


memcached服务器的安装请参考http://www.iteye.com/topic/1123037#2344649
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics