memcached下载地址:
http://memcached.org/
libevent下载地址:
http://libevent.org/
关联下载:http://download.csdn.net/download/cheney1993/10027954
检查下本地是否已经安装了libevent,命令:rpm -qa|grep libevent
既然已经安装了一个版本的libevent,那么我们就先将其卸载后再安装我们自己的libevent,卸载命令如下:
rpm -e --nodeps libevent-1.4.13-4.el6.x86_64
加载libevent依赖库,命令:yum -y install libevent-devel
解压缩libevent包
切换到解压缩文件根目录
指定安装位置并开始安装和编译:
./configure --prefix=/usr/local/libevent
make
make install
接着安装memcached
make
make install
开始启动memcached,cd /usr/local/memcached/bin
执行命令:./memcached -u root -d (-u指由root用户启动,-d是保护进程)
检测memcached服务是否启动,查看进程,命令:netstat -ntlp|grep memcached
或 ps -ef|grep memcached
------------------------------------客户端检测----------------------------------------
依赖的jar
Memcached缓存String代码测试:
package com.axb.cheney.test;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MyCache {
public static void main(String[] args) {
MemCachedClient client=new MemCachedClient();
String [] addr ={"192.168.75.128:11211"};
Integer [] weights = {3};
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(addr);
pool.setWeights(weights);
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(200);
pool.setMaxIdle(1000*30*30);
pool.setMaintSleep(30);
pool.setNagle(false);
pool.setSocketTO(30);
pool.setSocketConnectTO(0);
pool.initialize();
// 将数据放入缓存
client.set("str1","缓存字符串");
// 将数据放入缓存,并设置失效时间
Date date=new Date(2000000);
client.set("str2","str2", date);
// 删除缓存数据
// client.delete("str1");
// 获取缓存数据
String str =(String)client.get("str1");
System.out.println(str);
}
}
查看输出:
Memcached缓存java bean自定义对象代码测试:
新增bean类:
public class TestBean implements Serializable {
private static final long serialVersionUID = 6362340607343002961L;
private String name;
private Integer age;
//省略get、set
}
主main:
package com.axb.cheney.test;
import java.io.Serializable;
import java.util.Date;
import com.axb.cheney.bean.TestBean;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MyCacheBean {
/**
* Memcached可以缓存String,也可以缓存自定义java bean。
* 但必须是可序列化的java bean(implements Serializable即可)
* @cheney
*/
public static void main(String[] args) {
MemCachedClient client=new MemCachedClient();
String [] addr ={"192.168.75.128:11211"};
Integer [] weights = {3};
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(addr);
pool.setWeights(weights);
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(200);
pool.setMaxIdle(1000*30*30);
pool.setMaintSleep(30);
pool.setNagle(false);
pool.setSocketTO(30);
pool.setSocketConnectTO(0);
pool.initialize();
// 将数据放入缓存
TestBean bean=new TestBean();
bean.setName("cheney");
bean.setAge(25);
client.add("bean1", bean);
// 获取缓存数据
TestBean beanClient=(TestBean)client.get("bean1");
System.out.println(beanClient.getName()+",age:"+beanClient.getAge());
}
}
输出: