package cc.smtweb.framework.core.cache;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Akmm at 2022/3/14 10:42
 */
public class SessionCacheFactory {
    private static SessionCacheFactory INSTANCE = null;
    private Map<String, SessionCache> buffer = new ConcurrentHashMap<>();

    private SessionCacheFactory() {
    }

    /*获取单例*/
    public static SessionCacheFactory getInstance() {
        if (INSTANCE == null) {
            synchronized (SessionCacheFactory.class) {
                if (INSTANCE == null) {
                    INSTANCE = new SessionCacheFactory();
                }
            }
        }
        return INSTANCE;
    }

    //得到用户缓存对象
    public SessionCache getUserCache(long userId) {
        return getCache(String.valueOf(userId), 0L);
    }

    public SessionCache getCache(String userId, long timeout) {
        SessionCache cache;

        cache = buffer.get(userId);
        if (cache == null) {
            cache = buffer.get(userId);
            if (cache != null) return cache;
            cache = new SessionCache(timeout);
            buffer.put(userId, cache);
        }
        return cache;
    }

    //删除用户缓存
    public void remove(String userId) {
        buffer.remove(userId);
    }


}
