java与memcached交互实例

本文介绍如何使用Memcached库实现简单的缓存操作,包括添加、获取和更新缓存值,并通过实例演示了如何在Java环境中配置和使用Memcached。
 
 
package com.test.memcached;


import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class MemcacheHandle {
static private MemcacheHandle ins ;
private  MemCachedClient memCachedClient = new MemCachedClient();
private MemcacheHandle() {	
}
//获得一个单例的缓存
public static MemCachedClient getCache(){
	if(ins==null){
		ins = new MemcacheHandle();
	}
	return ins.memCachedClient;
}
static {
	String[] servers = { "127.0.0.1:11211" };
	SockIOPool pool = SockIOPool.getInstance();
	pool.setServers( servers );
	pool.setFailover( true );
	pool.setInitConn( 10 ); 
	pool.setMinConn( 5 );
	pool.setMaxConn( 250 );
	pool.setMaintSleep( 30 );
	pool.setNagle( false );
	pool.setSocketTO( 3000 );
	pool.setAliveCheck( true );
	pool.initialize();	
}
public static void main(String[] args) {
	 MemCachedClient mem = MemcacheHandle.getCache();
	String str = "hello world";
	System.out.println("local value:\t"+str);
	mem.add("cache.str", str);
	str = (String)mem.get("cache.str");
	System.out.println("memcached value:\t"+str);
	str = "new str";
	System.out.println("local value:\t"+str);
	str = (String)mem.get("cache.str");
	System.out.println("memcached value:\t"+str);
}
}


 

直接上代码。非常简单,注意要引用java_memcached-release_1.6.jar

运行后:

local value: hello worldcom.danga.MemCached.MemCachedClient Tue Jan 10 18:06:47 CST 2012 - Storing with native handler...com.danga.MemCached.MemCachedClient Tue Jan 10 18:06:47 CST 2012 - ++++ memcache cmd (result code): add cache.str 0 0 12 (NOT_STORED)com.danga.MemCached.MemCachedClient Tue Jan 10 18:06:47 CST 2012 - ++++ data not stored in cache for key: cache.strmemcached value: hello worldlocal value: new strmemcached value: hello world

 



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值