结合ehcache缓存对lucene使用单例模式搜索

我采用和ehcache缓存结合使用单例模式,其实就是给indexsearcher加了个缓存

使用ehcache在内存中设置一个缓存,时间为10分钟。

当IndexSearcher对象不存在时,创建静态对象同时在缓存中写入一个值,表示对象已经存在了.

搜索时如果缓存过期,则重新创建IndexSearcher
public class MySearcher {
	private IndexSearcher searcher = null;
	private static MySearcher mySearcher = null;
	public static MySearcher getInstance() throws IOException{
		CacheManager manager = CacheManager.getInstance(); 
		net.sf.ehcache.Cache cache = manager.getCache("seacher_cache");
		String seacherKey = "Searcher_Id";
		net.sf.ehcache.Element searchElement = cache.get(seacherKey); 
        if (mySearcher==null || searchElement==null){
          mySearcher = new MySearcher();
        	searchElement = new net.sf.ehcache.Element(seacherKey,1); 
    		cache.put(searchElement);
    		
        }
        return mySearcher;
    }
    public MySearcher() throws IOException{
		this.searcher = new IndexSearcher("d:/index");
    }
}
 

相关推荐