package cn.com.capcloud.core.system.configuration;

import org.springframework.cache.concurrent.ConcurrentMapCache;

import java.util.concurrent.TimeUnit;

/**
 * @Author LiaoJiaHui
 * @Create 2025/5/29
 */
public class ExpiringCache extends ConcurrentMapCache {

    private final long expireAfterWriteSeconds;

    public ExpiringCache(String name, long expireAfterWriteSeconds) {
        super(name);
        this.expireAfterWriteSeconds = expireAfterWriteSeconds;
    }

    @Override
    public void put(Object key, Object value) {
        super.put(key, value);
        // 定期清理缓存
        scheduleEviction(key);
    }

    private void scheduleEviction(Object key) {
        // 启动一个定时任务，用于清除过期缓存
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(expireAfterWriteSeconds);
                evict(key);  // 超过过期时间后清除缓存
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void evict(Object key) {
        this.getNativeCache().remove(key);
    }
}
