Memcached是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。
1、linux环境下安装与启动memcache:
以编译安装的方式安装。具体参看:
【我没有安装检验过】
一个服务器上可以启动多个memcached服务,设置不同的端口号即可。
启动memcached 11211端口
/usr/local/memcached/bin/memcached -p11211 -d -r -u root -vv>>m.log 2>&1
2、java代码连接memcached服务
(1)引入jar包 :java_memcached-release_2.6.6.jar, 开源代码,可去官网下载jar包
(2)new SockIOPool 和 new MemCachedClient
static{// 应用服务器对数据库的增删改查都要与之先建立数据库连接,有了pool,才会有连接sockIoPool= init(poolName,"cacheServers");
memCachedClient= newMemCachedClient(poolName);//设置cache 数据的原始类型是String .//默认值是false 只有在确定cache 的数据类型是string 的情况下才设为true,这样可以加快处理速度。
memCachedClient.setPrimitiveAsString(true);
}public staticSockIOPool init(String poolName, String confKey){//缓存服务器
String cacheServers=GameServer.cfg.getServerByName(confKey);
String server[]= {"192.x.x.x:11211"};if (cacheServers == null || "".equals(cacheServers)) {
}else{
server[0]=cacheServers;
}//创建一个连接池
SockIOPool pool =SockIOPool.getInstance(poolName);
pool.setServers(server);//缓存服务器
pool.setInitConn(50); //初始化链接数
pool.setMinConn(50); //最小链接数
pool.setMaxConn(500); //最大连接数
pool.setMaxIdle(1000 * 60 * 60);//最大处理时间
pool.setMaintSleep(3000);//设置主线程睡眠时,每3秒苏醒一次,维持连接池大小
pool.setNagle(false);//关闭套接字缓存
pool.setSocketTO(3000);//链接建立后超时时间
pool.setSocketConnectTO(0);//链接建立时的超时时间
pool.initialize();returnpool;
}
/*
set和add最显而易见的区别就是:
如果key是已经存在的set是更新原来的数据,而add则不会。
所以对于add的对象有replace方法
*/
public boolean add(String key , Object o){
return memCachedClient.add(key, o);
}
public boolean set(String key , Object o){
return memCachedClient.set(key, o);
}
public boolean update(String key , Object o){
return memCachedClient.replace(key, o);
}
public boolean delete(String key){
return memCachedClient.delete(key);
}
/*memCachedClient还有计数的方法: incr("key", 1L); getCount("key")*/
3、 对类、临时数据等进行缓存:新建一个类,建立一个cachedClass set,将需要缓存的类全部add进去,主要是为了便于管理
public static Set> cachedClass = new HashSet();
static{
System.out.print("static 被执行");
cachedClass.add(Player.class);
cachedClass.add(User.class);
}
// 在新new一个对象的时候,可以调用add方法,之后可用update,delete...方法对对象数据进行增删改查的操作
一份数据在memcached缓存之后,并存入数据库,那么在数据库本地更改数据不能更改缓存,也就是要看缓存和db的关系。
4、情况memcached缓存数据:
(1) kill 掉进程,就关闭,并且清空了memcache缓存中所有的数据,但是这就关掉了memcached进程了。
(2)flush_all :flush并不会将items删除,只是将所有的items标记为expired,因此这时memcache依旧占用所有内存。
【memcached 中一个命令flush_all 执行前后,使用stats查看的状态完全一样,刚开始以为是没执行成功,学习完memcached的工作原理后发现了flush_all执行完的效果是这样的:
“flush_all”命令有一个可选的数字参数。它总是执行成功,服务器会发送“OK\r\n”回应。它的效果是使已经存在的项目立即失效(缺省),或在指定的时间后。此后执行取回命令,将不会有任何内容返回(除非重新存储同样的键名)。flush_all 实际上没有立即释放项目所占用的内存,而是在随后陆续有新的项目被储存时执行。flush_all 效果具体如下:它导致所有更新时间早于flush_all所设定时间的项目,在被执行取回命令时命令被忽略。】