使用Memcache缓存提升搜索引擎项目性能
搜索项目已经上线了,客户使用的硬件不错,系统表现的也不错,不过所谓”编程无止境”,针对客户的使用特点,我决定对系统做个使用Memcache缓存提升性能的方案,对于整个搜索系统来说需要缓存的地方很多:搜索结果、分词(同义词)、以及客户定制的一些功能.本文就针对搜索结果做缓存看看性能提升效果 .
Memcache服务器使用很简单从http://memcached.org/ 下载,开启服务的简单命令:/path/to/memcached -u root -d,JAVA-Client可以使用这个:http://github.com/gwhalin/Memcached-Java-Client/downloads.
根据系统需求,写一个CacheUtil类,根据搜索关键字+搜索类型+搜索起始记录数 组成的字符串作为key,保存搜索结果HashMap,同样根据key取得搜索结果直接返回.
package com.richeninfo.sw.search;
import java.util.HashMap;
import java.util.Map;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class CacheUtil {
protected static MemCachedClient mcc = new MemCachedClient();
private static String[] servers = {"localhost:11211"};
private static Integer[] weights = {3};
static {
//需要写成配置,测试数据
//String[] servers = {"localhost:11211"};
//Integer[] weights = {3};
//创建一个实例对象SockIOPool
SockIOPool pool = SockIOPool.getInstance();
// set the servers and the weights
//设置Memcached Server
pool.setServers(servers);
pool.setWeights(weights);
// set some basic pool settings
// 5 initial, 5 min, and 250 max conns
// and set the max idle time for a conn
// to 6 hours
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000 * 60 * 60 * 6);
// set the sleep for the maint thread
// it will wake up every x seconds and
// maintain the pool size
pool.setMaintSleep(30);
// Tcp的规则就是在发送一个包之前,本地机器会等待远程主机
// 对上一次发送的包的确认信息到来;这个方法就可以关闭套接字的缓存,
// 以至这个包准备好了就发;
pool.setNagle(false);
//连接建立后对超时的控制
pool.setSocketTO(3000);
//连接建立时对超时的控制
pool.setSocketConnectTO(0);
// initialize the connection pool
//初始化一些值并与MemcachedServer段建立连接
pool.initialize();
// lets set some compression on for the client
// compress anything larger than 64k
mcc.setCompressEnable(true);
mcc.setCompressThreshold(64 * 1024);
}
public Map get(String key,int type,int start){
String tempKey = "k:" + key + "t:" + new Integer(type) + "s:" + new Integer(start);
return get(tempKey);
}
public Map get(String key) {
return (Map) mcc.get(key);
}
public void put(String key,int type,int start,Map value){
String tempKey = "k:" + key + "t:" + new Integer(type) + "s:" + new Integer(start);
put(tempKey,value);
}
public void put(String key, Map value) {
if (needCache(key)) {
mcc.set(key, value);
}
}
public boolean needCache(String key) {
return true;
}
public static void main(String [] args){
CacheUtil cu = new CacheUtil();
String key = "k:中国t:1s:1";
Map map = new HashMap();
map.put("key", 123);
CacheUtil.mcc.set(key, map);
Map v = (Map) CacheUtil.mcc.get(key);
System.out.println("v = " + v);
}
}
其中更具业务需求去缓存(needCache),比如只缓存热门关键词等.结合到系统中测试,在搜索前先取缓存,如果没有缓存再搜索,搜索后对结果缓存.简单的测试结果:
第一次搜索linux:
第二次搜索linux:
第一次搜索”5″:
第二次搜索”5″:
从测试结果看,对性能提升还是有大的作用的,对于集成到系统中,也不是简单的加个类就好,要对系统做整体的缓存设计,所以还得做比较多的事情.
文章作者:liangdi 最后修改:2010.04.18 转载请注明来自:[自由的心灵]
原文链接:http://liangdi.icentos.net/2010/04/18/use_memcache_nutch_lucene/




近期评论