IndexRebuildJob.java 2.82 KB
package com.yohomars.search.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.yohomars.search.index.service.IYohoIndexService;
import com.yohomars.search.utils.Index;

/**
 * 定时任务
 */
@Component
public class IndexRebuildJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexRebuildJob.class);

    @Autowired
    private IYohoIndexService yohoIndexService;


    /**
     * 定时任务重建索引(每1小时执行一次)
     * 用于重建数据量大的索引
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void rebuildIndexJob() {
        this.rebuildIndex(Index.social_user);
    }

    /**
     * 定时任务重建索引(每10分钟执行一次)
     * 用于重建数据量小的索引
     */
    @Scheduled(cron = "0 */10 * * * ?")
    public void rebuildSmallIndexJob() {
        this.rebuildIndex(Index.store);
        this.rebuildIndex(Index.content);
    }

    /**
     * 定时任务增量更新索引(每10分钟执行一次)
     */
    @Scheduled(cron = "50 */10 * * * ?")
    public void appendIndexJob() {
        //this.appendIndex(Index.social_user);
        this.appendIndex(Index.content);
    }

    /**
     * 重建索引
     */
    private void rebuildIndex(Index index) {
        try {
            if(index==null){
                LOGGER.error("rebuildIndex failed with index==null");
                return;
            }
            String indexName = index.getIndexName();
            yohoIndexService.rebuildIndex(indexName);
            
            
            
//            RunnableQueueFactory.getInstance().addTask(indexName, new Runnable() {
//                @Override
//                public void run() {
//                    yohoIndexService.rebuildIndex(indexName);
//                }
//            });
        } catch (Exception e) {
            LOGGER.error("rebuildIndex error,cause:", e);
        }
    }

    /**
     * 增量更新索引
     * @param index
     */
    private void appendIndex(Index index){
        try {
            if(index==null){
                LOGGER.error("buildAppendedIndex failed with index==null");
                return;
            }
            String indexName = index.getIndexName();
            yohoIndexService.appendIndex(indexName);
            
            
            
//            RunnableQueueFactory.getInstance().addTask(indexName, new Runnable() {
//                @Override
//                public void run() {
//                    yohoIndexService.appendIndex(indexName);
//                }
//            });
        } catch (Exception e) {
            LOGGER.error("buildAppendedIndex error,cause:", e);
        }
    }


}