1 memcache会依赖libevent
brew install libevent
2 下载memcache
#wget
然后configure;make;make install安装
3 启动:
`sudo ./memcached -p 11211 -m 64 -u shenyb -d soft ps -ef |grep memcache :40上午 ??0:00.16 ./memcached -p 11211 -m 64 -u shenyb -d`
可以看到memcache已经启动。 4使用java客户端连接测试 Java客户端: 目前主要有两种客户端: <1>. https://github.com/gwhalin/Memcached-Java-Client/ <2>. 会依赖spy.jar 两种差别不大,只是set时过期时间设置方式不同,效率没有测试过。 这里使用第一种: 测试代码如下:
import java.util.Date;import com.danga.MemCached.MemCachedClient;import com.danga.MemCached.SockIOPool;public class MemcacheUtil {() throws Exception {/* 初始化SockIOPool,管理memcached的连接池 */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);// 设置主线程睡眠时间,每30秒苏醒一次,维持连接池大小pool.setMaintSleep(30);// 关闭套接字缓存pool.setNagle(false);// 连接建立后的超时时间pool.setSocketTO(3000);pool.setAliveCheck(true);pool.initialize();/* 建立MemcachedClient实例 */MemCachedClient memCachedClient = new MemCachedClient();long start = System.currentTimeMillis();for (int i = 0; i < 1000; i++) {memCachedClient.set(i + “”, “hello” + i);}for (int i = 0; i < 1000; i++) {System.out.println(memCachedClient.get(i + “”));}long end = System.currentTimeMillis();System.out.println((end – start));memCachedClient.set(“name1”, “test22”,new Date(System.currentTimeMillis() + 3000));Thread.sleep(2000);System.out.println(memCachedClient.get(“name1”));}(String[] args) {try {testDanga();} catch (Exception e) {e.printStackTrace();}}}
关于设置过期时间:
client.set(key, value, new Date(expireTime));
但这个时间如何设置,还是有一点区别,比如设置10分钟后过期,是应该设置date为System.currentTimeInMillis()+10*60*1000 还是10*60*1000 服务端是两种方式都兼容的,,一个是多少秒后过期,一个是什么时候过期, 但后者因为设置时间是在客户端,存储在服务端,假如两台服务器时间差别很大,就会导致数据的过期时间和我要求的时间点不符合。
最后,memcache一般用来存储不怎么变化的数据,比如网站栏目信息,商品的属性信息,网站页脚等。
背起简单的行攘,沐浴自由的风。