SuggestionCounterJob.java 2.79 KB
package com.yoho.search.consumer.job;

import com.yoho.search.consumer.suggests.common.RetryBusinessFlowExecutor;
import com.yoho.search.consumer.suggests.common.SuggestionConstants;
import com.yoho.search.consumer.suggests.counter.AbstractSuggestionCounter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class SuggestionCounterJob implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger("FLOW_EXECUTOR");

    private List<RetryBusinessFlowExecutor> flowExecutorList = new ArrayList<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, AbstractSuggestionCounter> beanMap = applicationContext.getBeansOfType(AbstractSuggestionCounter.class);
        if (beanMap == null || beanMap.isEmpty()) {
            logger.warn("There is no suggestion counter defined.");
            return;
        }

        flowExecutorList = beanMap.values().stream()
                .map(counter -> new RetryBusinessFlowExecutor(counter, SuggestionConstants.SUGGESTION_COUNT_BATCH_MAX_THREAD_SIZE, SuggestionConstants.SUGGESTION_COUNT_BATCH_LIMIT))
                .collect(Collectors.toList());
    }

    @Scheduled(cron = "0 30 3 * * ?")
    public void execute() {
        long begin = System.currentTimeMillis();
        logger.info("SuggestionCounterJob execute start----[begin={}]", begin);
        boolean result = true;
        for (RetryBusinessFlowExecutor executor : flowExecutorList) {
            boolean tempResult = executor.execute();
            if (!tempResult) {
                logger.warn("SuggestionCounterJob execute has failure----[bean={}]", executor.getFlowName());
            }
            result = result && tempResult;
        }
        logger.info("SuggestionCounterJob execute end----[cost={}][result={}]", (System.currentTimeMillis() - begin), result);
    }

    public void executeFlow(String flowName) {
        long begin = System.currentTimeMillis();
        logger.info("SuggestionCounterJob executeFlow start----[begin={}]", begin);
        Optional<RetryBusinessFlowExecutor> executor = flowExecutorList.stream().filter(item -> flowName.equals(item.getFlowName())).findAny();
        executor.ifPresent(RetryBusinessFlowExecutor::execute);
        logger.info("SuggestionCounterJob executeFlow end----[cost={}]", (System.currentTimeMillis() - begin));

    }
}