package com.ytpm.question.config.redis;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ytpm.question.redis.RedisService;
import com.ytpm.util.ResourceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author lih
 * @date 2025-11-11 14:00
 */
@Slf4j
@Component
public class RedisCacheInitializer {
    @Resource
    private RedisService redisService;

    @Value("${spring.application.name:}")
    private String applicationName;

    @Value("${spring.config.black-ip.file-name:blackIpList.txt}")
    private String configFileName;

    @EventListener(ApplicationReadyEvent.class)
    public void initRedisCache() {
        try {
            List<String> strings = ResourceUtils.readFileToList(configFileName);
            if (CollectionUtils.isNotEmpty(strings)) {
                String serviceName = StrUtil.replace(applicationName, "-service", "");
                String cacheKey = StrUtil.format("blackIps:{}", serviceName);
                redisService.setStr(cacheKey, String.join(",", strings));
                log.info("已加载IP黑名单:{}", String.join(",", strings));
            }
        } catch (IOException ignored) {}
    }
}
