项目是体量不大的项目,没有条件使用es,此处展示Lucene实现全过程,有疑问请评论,看到即解答
发文只因网上自己没搜到,可以提供个参考,本人水平一般,有待改进之处还往大佬指出
导入依赖和分词器这些省略,直接进入AOP部分
1,新建注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LuceneCreate
{
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LuceneUpdate
{
}
2,AOP方法
@Aspect
@Component
public class LuceneAspect
{
@Autowired
private LuceneService luceneService;
@Autowired
private WorksService worksService;
@Pointcut("@annotation(com.ztower.common.annotation.LuceneCreate)")
public void createPointCut() {}
@Pointcut("@annotation(com.ztower.common.annotation.LuceneUpdate)")
public void updatePointCut() {}
@AfterReturning("createPointCut()")
public void LuceneCreate(JoinPoint joinPoint)
{
//System.out.println("createPointCut");
Object[] args = joinPoint.getArgs();
WorksDO works = (WorksDO)args[0];
luceneService.saveWorks(works);
}
@AfterReturning("updatePointCut()")
public void LuceneUpdate(JoinPoint joinPoint)
{
//System.out.println("updatePointCut");
Object[] args = joinPoint.getArgs();
WorksDO works = (WorksDO)args[0];
luceneService.updateWorks(works);
}
}
3,新建包装类
@Data
public class WorksObject implements Comparable<WorksObject>
{
private String id;
private String title;
private String type;
private String author;
private String org;
private String postDate;
private String status;
private float score;
public WorksObject(WorksDO works)
{
super();
this.id = works.getWorksId();
this.author = works.getWorksUserName();
this.org = works.getWorksOrgName();
this.postDate = strToday();
this.status = works.getWorksStatus().toString();
this.type = "works";
}
@Override
public int compareTo(WorksObject o)
{
if(this.score < o.getScore()){
return 1;
}else if(this.score > o.getScore()){
return -1;
}
return 0;
}
4,在保存方法上添加注解
@LuceneCreate
@ResponseBody
@PostMapping("/saveWorks")
public R saveWorks( @RequestParam Map<String, Object> params)
{
....
}
5,创建索引文件
public void create(WorksDO works) {
WorksObject worksObject = new WorksObject(works);
IndexWriter indexWriter = null;
try {
IndexWriterConfig config = new IndexWriterConfig(this.getAnalyzer());
indexWriter = new IndexWriter(this.getDirectory(), config);
indexWriter.addDocument(DocumentUtil.WorksObject2Document(worksObject));
indexWriter.commit();
} catch (Exception e) {
System.out.println("创建索引库失败");
e.printStackTrace();
if(indexWriter!=null){
try {
indexWriter.rollback();
} catch (IOException e1) {
System.out.println("写入索引库失败");
e1.printStackTrace();
}
}
}finally {
if(indexWriter!=null){
try {
indexWriter.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}