RedisCacheManager.java
2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.huaheng.framework.redis;
import com.huaheng.common.utils.RedisUtils;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Component
public class RedisCacheManager implements CacheManager
{
    private final Logger logger = LoggerFactory.getLogger(RedisCacheManager.class);
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap();
    @Autowired
    private RedisUtils redisUtils;
    public static final String DEFAULT_CACHE_KEY_PREFIX = "shiro:redisCache:";
    private String keyPrefix = DEFAULT_CACHE_KEY_PREFIX;
    // expire time in seconds
    public static final long DEFAULT_EXPIRE = 30 * 60 * 1000;
    @Value("${redis.timeout}")
    private long expire ;
    public static final String DEFAULT_PRINCIPAL_ID_FIELD_NAME = "authCacheKey or id";
    private String principalIdFieldName = DEFAULT_PRINCIPAL_ID_FIELD_NAME;
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException
    {
        this.logger.debug("get cache, cacheName=" + cacheName);
        Cache cache = (Cache) this.caches.get(cacheName);
        if (cache == null)
        {
            this.logger.debug("get cache but cache is null");
            cache = new ShiroRedisCache(this.redisUtils, this.keyPrefix + cacheName + ":", expire,
                    this.principalIdFieldName);
            this.caches.put(cacheName, cache);
        }
        return (Cache) cache;
    }
    public String getKeyPrefix()
    {
        return keyPrefix;
    }
    public void setKeyPrefix(String keyPrefix)
    {
        this.keyPrefix = keyPrefix;
    }
    public long getExpire()
    {
        return expire;
    }
    public void setExpire(long expire)
    {
        this.expire = expire;
    }
    public String getPrincipalIdFieldName()
    {
        return principalIdFieldName;
    }
    public void setPrincipalIdFieldName(String principalIdFieldName)
    {
        this.principalIdFieldName = principalIdFieldName;
    }
    public void setRedisUtils(RedisUtils redisUtils)
    {
        this.redisUtils = redisUtils;
    }
}