work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java 使用Memcache

Posted on 2016-12-21 19:41  work hard work smart  阅读(329)  评论(0编辑  收藏  举报

使用spymemcached.jar

public class MemcachedJava {

	public static void main(String[] args) {
		try {
			 // 连接本地的 Memcached 服务
			MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			System.out.println("Connecton to server successful");
			
			// 查看存储状态
			Future fu = mcc.set("news", 900, "There is a import news today!");
			System.out.println("get Status: " + fu.get());
			System.out.println("获得news的值: "+ mcc.get("news"));
			
			mcc.add("news", 900, "Second news");
			System.out.println("get Status: " + fu.get());
			System.out.println("获得news的值: "+ mcc.get("news"));
			System.out.println("-------------------------");
			
			
			//mcc.add("today", 900, "today news 59595");
			System.out.println("get Status: " + fu.get());
			System.out.println("获得today的值: "+ mcc.get("today"));
			System.out.println("-------------------------");
			
			//Replace
			mcc.replace("today", 900, "today news abcd576457");
			System.out.println("get Status: " + fu.get());
			System.out.println("获得today的值: "+ mcc.get("today"));
			System.out.println("-------------------------");
			
			//Append 
			mcc.append("today", "[Append contenet!]");
			System.out.println("get Status: " + fu.get());
			System.out.println("获得today的值: "+ mcc.get("today"));
			System.out.println("-------------------------");
			
			//Prepend
			mcc.prepend("today", "[Prepend contenet] ");
			System.out.println("get Status: " + fu.get());
			System.out.println("获得today的值: "+ mcc.get("today"));
			System.out.println("-------------------------");
			
			//CAS 操作实例
			CASValue casValue  = mcc.gets("today");
			// 输出 CAS token(令牌) 值
	        System.out.println("CAS token - " + casValue);
	        
	        CASResponse casResponse = mcc.cas("today", casValue.getCas(), 900,"[Changed today data]Change data by cas");
	        
	        // 输出 CAS 响应信息
	        System.out.println("CAS Response - " + casResponse);
	        System.out.println("获得today的值: "+ mcc.get("today"));
			System.out.println("-------------------------");
			
			// 关闭连接
			mcc.shutdown();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}
		

	}

}