设计良好的线程模式保证lucene的运行不影响原本项目的性能。而且大大降低了lucene和项目之间的耦合度。
索引的操作线程:
一下代码是从网上剪切过来的,可能有错误,但是原理都是一样的,明白了原理,什么都简单。稍后我会将我自己写的几个测试代码贴上去,可以 关注下后面的文字
public class MyIndexOperateThread extends Thread {
private static Logger logger = LogManager
.getLogger(MyIndexOperateThread.class);
private Object obj;
private String str;
private Long id;
private List<Long> ids;
private Operate operate;
/**
* 枚举
*
* @author wangrenhui
*
*/
public enum Operate {
update, delete, add
}
/**
* @param operate 更新和添加操作
* @param obj 更新的对象
* @param moduleMark 模块标示
*/
public MyIndexOperateThread(Operate operate, Object obj, String moduleMark) {
this.operate = operate;
this.obj = obj;
this.str = moduleMark;
}
/**
*
* @param operate 操作
* @param id id
* @param className 类名
*/
public MyIndexOperateThread(Operate operate, Long id, String className) {
this.operate = operate;
this.id = id;
this.str = className;
}
/**
*
* @param operate 删除操作
* @param ids id集合
* @param className 类名
*/
public MyIndexOperateThread(Operate operate, List<Long> ids,
String className) {
this.operate = operate;
this.ids = ids;
this.str = className;
}
@Override
public void run() {
try {
if (operate == Operate.delete) {
if (id != null) {
IndexCreateUtil.deleteDocument(id, str);
} else if (ids != null) {
IndexCreateUtil.deleteDocument(ids, str);
}
} else if (operate == Operate.update) {
IndexCreateUtil.updateDocument(obj, str);
} else if (operate == Operate.add) {
IndexCreateUtil.addDocument(obj, str);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
} finally {
MyIndexWriter.close(); // 注意不是调用 IndexWriter.Close() !
}
}
}
数据持久层的使用:
/**
*
* @function 更新处方
* @param prescription 处方对象
*/
public void updatePrescription(Prescription prescription) {
this.getHibernateTemplate().update(prescription);
try {
MyIndexOperateThread indexOperateThread = new MyIndexOperateThread(Operate.update, prescription, "Prescription");//更新索引的线程
indexOperateThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}