liuxiaolong
2019-05-09 0d1d88cdb668e75ea8609417ac18ae19947e9525
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.common.security.shiro.cache;
 
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
 
import javax.servlet.http.HttpServletRequest;
 
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 redis.clients.jedis.Jedis;
 
import com.google.common.collect.Sets;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.web.Servlets;
 
/**
 * 自定义授权缓存管理类
 * @author jeeplus
 * @version 2014-7-20
 */
public class JedisCacheManager implements CacheManager {
 
    private String cacheKeyPrefix = "shiro_cache_";
    
    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {
        return new JedisCache<K, V>(cacheKeyPrefix + name);
    }
 
    public String getCacheKeyPrefix() {
        return cacheKeyPrefix;
    }
 
    public void setCacheKeyPrefix(String cacheKeyPrefix) {
        this.cacheKeyPrefix = cacheKeyPrefix;
    }
    
    /**
     * 自定义授权缓存管理类
     * @author jeeplus
     * @version 2014-7-20
     */
    public class JedisCache<K, V> implements Cache<K, V> {
 
        private Logger logger = LoggerFactory.getLogger(getClass());
 
        private String cacheKeyName = null;
 
        public JedisCache(String cacheKeyName) {
            this.cacheKeyName = cacheKeyName;
//            if (!JedisUtils.exists(cacheKeyName)){
//                Map<String, Object> map = Maps.newHashMap();
//                JedisUtils.setObjectMap(cacheKeyName, map, 60 * 60 * 24);
//            }
//            logger.debug("Init: cacheKeyName {} ", cacheKeyName);
        }
        
        @SuppressWarnings("unchecked")
        @Override
        public V get(K key) throws CacheException {
            if (key == null){
                return null;
            }
            
            V v = null;
            HttpServletRequest request = Servlets.getRequest();
            if (request != null){
                v = (V)request.getAttribute(cacheKeyName);
                if (v != null){
                    return v;
                }
            }
            
            V value = null;
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                value = (V)JedisUtils.toObject(jedis.hget(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key)));
                logger.debug("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "");
            } catch (Exception e) {
                logger.error("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "", e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            
            if (request != null && value != null){
                request.setAttribute(cacheKeyName, value);
            }
            
            return value;
        }
 
        @Override
        public V put(K key, V value) throws CacheException {
            if (key == null){
                return null;
            }
            
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                jedis.hset(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key), JedisUtils.toBytes(value));
                logger.debug("put {} {} = {}", cacheKeyName, key, value);
            } catch (Exception e) {
                logger.error("put {} {}", cacheKeyName, key, e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return value;
        }
 
        @SuppressWarnings("unchecked")
        @Override
        public V remove(K key) throws CacheException {
            V value = null;
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                value = (V)JedisUtils.toObject(jedis.hget(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key)));
                jedis.hdel(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key));
                logger.debug("remove {} {}", cacheKeyName, key);
            } catch (Exception e) {
                logger.warn("remove {} {}", cacheKeyName, key, e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return value;
        }
 
        @Override
        public void clear() throws CacheException {
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                jedis.hdel(JedisUtils.getBytesKey(cacheKeyName));
                logger.debug("clear {}", cacheKeyName);
            } catch (Exception e) {
                logger.error("clear {}", cacheKeyName, e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
        }
 
        @Override
        public int size() {
            int size = 0;
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                size = jedis.hlen(JedisUtils.getBytesKey(cacheKeyName)).intValue();
                logger.debug("size {} {} ", cacheKeyName, size);
                return size;
            } catch (Exception e) {
                logger.error("clear {}",  cacheKeyName, e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return size;
        }
 
        @SuppressWarnings("unchecked")
        @Override
        public Set<K> keys() {
            Set<K> keys = Sets.newHashSet();
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                Set<byte[]> set = jedis.hkeys(JedisUtils.getBytesKey(cacheKeyName));
                for(byte[] key : set){
                    keys.add((K)key);
                }
                logger.debug("keys {} {} ", cacheKeyName, keys);
                return keys;
            } catch (Exception e) {
                logger.error("keys {}", cacheKeyName, e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return keys;
        }
 
        @SuppressWarnings("unchecked")
        @Override
        public Collection<V> values() {
            Collection<V> vals = Collections.emptyList();;
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                Collection<byte[]> col = jedis.hvals(JedisUtils.getBytesKey(cacheKeyName));
                for(byte[] val : col){
                    vals.add((V)val);
                }
                logger.debug("values {} {} ", cacheKeyName, vals);
                return vals;
            } catch (Exception e) {
                logger.error("values {}",  cacheKeyName, e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return vals;
        }
    }
}