package com.mortals.xhx.queue.processing;

import com.mortals.xhx.queue.TbQueueMsg;
import com.mortals.xhx.utils.IotThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 消费服务抽象类
 *
 * @author: zxfei
 * @date: 2022/4/28 9:43
 */
@Slf4j
public abstract class AbstractConsumerService<N extends TbQueueMsg> {

    /**
     * 启动消费主线程服务
     */
    protected abstract void launchMainConsumers();
    /**
     * 停止消费主线程服务
     */
    protected abstract void stopMainConsumers();
    /**
     * 启动一组消费线程
     */
    protected abstract void launchConsumersList();

    /**
     * 消息线程池
     */
    protected volatile ExecutorService consumersExecutor;
    /**
     * 变量
     */
    protected volatile boolean stopped = false;

    public void init(String mainConsumerThreadName) {
        this.consumersExecutor = Executors.newCachedThreadPool(IotThreadFactory.forName(mainConsumerThreadName));
        launchMainConsumers();
    }



    @PreDestroy
    public void destroy() {
        stopped = true;
        stopMainConsumers();
        if (consumersExecutor != null) {
            consumersExecutor.shutdownNow();
        }

    }
}
