记一下Shiro重构之RedisCacheManager

2023-08-17 15:32:15 浏览数 (2)

代码语言:javascript复制
package com.ccb.web.shiro;

import com.ccb.web.configs.CsRedisUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

import org.springframework.beans.factory.annotation.Autowired;

import projects.core.config.cache.RedisUtil;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Redis缓存管理
 *
 * @author zhuyongsheng
 * @date 2019/8/13
 */
@Slf4j
@Data
public class RedisCacheManager implements CacheManager {

    @Autowired
    CsRedisUtil redisUtil;

    /**
     * fast lookup by name map
     */
    private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<>();

    // 默认超时时间
    private static final int DEFAULT_EXPIRE = 60*60;

    // 超时时间
    private int expire = DEFAULT_EXPIRE;

    // 默认 key 前缀
    public static final String DEFAULT_CACHE_KEY_PREFIX = "shiro:cache:";

    // key 前缀
    private String keyPrefix = DEFAULT_CACHE_KEY_PREFIX;

    //  默认 PRINCIPAL_ID
    public static final String DEFAULT_PRINCIPAL_ID_FIELD_NAME = "authCacheKey or id";

    // PRINCIPAL_ID
    private String principalIdFieldName = DEFAULT_PRINCIPAL_ID_FIELD_NAME;

    /**
     * 获取缓存
     *
     * @return org.apache.shiro.cache.Cache<K, V>
     * @author zhuyongsheng
     * @date 2019/8/15
     */
    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {
        Cache cache = caches.get(name);
        if (cache == null) {
            cache = new RedisCache<K, V>(keyPrefix   name   ":", expire, principalIdFieldName);
            caches.put(name, cache);
        }
        return cache;
    }
}

0 人点赞