package com.czg.log.producer;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.czg.config.RedisCst;
import com.czg.service.RedisService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * 日志通过redis队列，异步保存到数据库
 *
 * @author admin admin@cashier.com
 * @since 1.0.0
 */
@Component
public class LogProducer {
    @Resource
    private RedisService redisService;

    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNamePrefix("log-producer-pool").build();

    ExecutorService pool = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    /**
     * 保存Log到Redis消息队列
     */
    public void saveLog(String log) {
        String key = RedisCst.SYS_LOG_KEY;

        //异步保存到队列
        pool.execute(() -> redisService.leftPush(key, log, RedisService.NOT_EXPIRE));
    }
}