|
由于项目需要,今天学习了memcache的使用方法。
1. memcache的服务器端的安装
下载memcache for win32, 解压缩后,在cmd命令行敲入命令
memcache -start,
就可以启动服务器端程序
2. java客户端访问
2.1 下载memcache for java client的插件
本人使用的是http://www.whalin.com/memcached/#download下载的
版本号为java_memcached-release_2.0.1.jar
2.2 进行初始化
获得MemCachedClient对象
static{
连接服务器端:
SockIOPool pool = SockIOPool.getInstance();
设置server, weight
pool.setServer(), pool.setWeight()
)
2.3 pool.initialize(); 进行初始化动作
3. memcacheclient.set(key, value, expiredTime)
就是插入数据,key-value成对
和hashmap的思路一致
注意:如果要想对某个对象进行存取操作,该对象本身进行序列化处理,否则会报空指针异常。具体的办法实现seriable就可以。
4. memcacheclient.get(key)
根据key,得到value值
具体代码如下:
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MemcacheTest {
//获得关键客户端对象,方便后续的set,get方法
protected static MemCachedClient mcc = new MemCachedClient();
static{
String[] servers = {
"127.0.0.1:11211"
};
Integer[] weights = {
3
};
//单例模式,获得一个实例,关键c/s连接
SockIOPool pool = SockIOPool.getInstance();
//设置服务器和权重
pool.setServers(servers);
pool.setWeights(weights);
//设置基本配置
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000*60*60*6);
//设置主线程的休眠时间
pool.setMaintSleep(30);
//tcp发送规则
pool.setNagle(false);
//连接建立后的超时控制
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
//初始化设置
pool.initialize();
mcc.setCompressEnable(true);
mcc.setCompressThreshold(64*1024);
}
/**
* 往服务器端的cache插入数据
* 注意key-value成对插入
* 参数过期时间
*/
public static void buildCache(){
mcc.set("test", "this is my first test string", new Date(10000));
}
/**
* 取出远程服务器端的value
* 根据key, 取出value
* 并且打印
*/
public static void output(){
String value = (String) mcc.get("test");
System.out.println("value: "+ value);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long time = System.currentTimeMillis();
buildCache();
output();
System.out.println("it cost time: " + (System.currentTimeMillis() - time));
}
}
运行结果:
value: this is my first test string
it cost time: 109 |
|
|