memcache的简单使用及 插入对象的实现

由于项目需要,今天学习了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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值