package com.bootdo.common.utils;


import com.bootdo.portal.common.CommonConstants;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.net.URL;

/**
 * 缓存操作工具
 *
 * @author Mr.xiBel
 * @date 2022/5/11
 **/

public class EhcacheUtil {

    private static final String path = "/ehcache.xml";

    private final CacheManager manager;

    private static EhcacheUtil ehCache;

    private EhcacheUtil(String path) {
        URL url = getClass().getResource(path);
        manager = CacheManager.create(url);
    }

    public static EhcacheUtil getInstance() {
        if (ehCache == null) {
            ehCache = new EhcacheUtil(path);
        }
        return ehCache;
    }

    public void put(String cacheName, String key, Object value) {
        Cache cache = manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public Cache get(String cacheName) {
        return manager.getCache(cacheName);
    }

    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
    }

    /**
     * 设置token 用户信息
     *
     * @param token
     * @param clzss
     */
    public void putTokenUser(String token, Object clzss) {
        EhcacheUtil.getInstance().put(CommonConstants.CACHE_PORTAL_USER, token, clzss);
    }

    /**
     * 删除已登陆用户uid
     *
     * @param token
     */
    public void removeTokenUser(String token) {
        EhcacheUtil.getInstance().remove(CommonConstants.CACHE_PORTAL_USER, token);
    }


}
