package com.project.shiro.util.redis;


import cn.wisenergy.service.common.utils.redis.RedisClient;
import cn.wisenergy.service.common.utils.redis.RedisConsts;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ShiroRedisCacheManager implements CacheManager {

    private static final Logger logger = LoggerFactory.getLogger(ShiroRedisCacheManager.class);

    private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();

    //注入redisClient实例
    @Resource(name = "redisClient")
    private RedisClient redisClient;

    /**
     * shiro权限缓存前缀
     */
    private String keyPrefix = RedisConsts.ADMIN_SHIRO_REALM_KEY;


    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {

        logger.debug("获取名称为: " + name + " 的RedisCache实例");
        Cache c = caches.get(keyPrefix + name);
        if (c == null) {
            c = new ShiroRedisCache<K, V>(redisClient, keyPrefix);
            caches.put(keyPrefix + name, c);
        }
        return c;
    }

    public RedisClient getRedisClient() {
        return redisClient;
    }

    public void setRedisClient(RedisClient redisClient) {
        this.redisClient = redisClient;
    }

    public String getKeyPrefix() {
        return keyPrefix;
    }

    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }
}
