package cc.smtweb.framework.core.cache;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;

/**
 * Created by Akmm at 2022/3/14 10:22
 */
public class SessionCache {
    private Cache<String, Object> cache;

    public SessionCache(long timeout) {
        if (timeout <= 0L) timeout = Long.MAX_VALUE;
        this.cache = Caffeine.newBuilder()
                .expireAfterAccess(timeout, TimeUnit.MINUTES).build();
    }

    public void put(String id, Object bean) {
        if (bean != null) cache.put(id, bean);
    }

    public void remove(String id) {
        cache.invalidate(id);
    }

    public void clear() {
        cache.invalidateAll();
    }

    @SuppressWarnings({"unchecked"})
    public <T> T get(String id) {
        return (T) cache.getIfPresent(id);
    }
}
