一、前言
关于apace的shiro源码包org.apache.shiro.cache.Cache、org.apache.shiro.cache.CacheManager缓存及其管理接口,并通过org.apache.shiro.cache.MapCache、org.apache.shiro.cache.MemoryConstrainedCacheManager、org.apache.shiro.cache.AbstractCacheManager进行实现,详情参见源码说明部分。
二、源码说明
1.Cache、CacheManager定义接口
package org.apache.shiro.cache;@b@@b@import java.util.Collection;@b@import java.util.Set;@b@@b@ public interface Cache<K, V> {@b@ @b@ public V get(K key) throws CacheException;@b@@b@ @b@ public V put(K key, V value) throws CacheException;@b@@b@ @b@ public V remove(K key) throws CacheException;@b@@b@ @b@ public void clear() throws CacheException;@b@@b@ @b@ public int size();@b@@b@ @b@ public Set<K> keys();@b@@b@ @b@ public Collection<V> values();@b@}
package org.apache.shiro.cache;@b@ @b@public interface CacheManager {@b@@b@ @b@ public <K, V> Cache<K, V> getCache(String name) throws CacheException;@b@}
2.MapCache实现类(Cache接口)
package org.apache.shiro.cache;@b@@b@import java.util.Collection;@b@import java.util.Collections;@b@import java.util.Map;@b@import java.util.Set; @b@ @b@public class MapCache<K, V> implements Cache<K, V> {@b@ @b@ private final Map<K, V> map;@b@ @b@ private final String name;@b@@b@ public MapCache(String name, Map<K, V> backingMap) {@b@ if (name == null) {@b@ throw new IllegalArgumentException("Cache name cannot be null.");@b@ }@b@ if (backingMap == null) {@b@ throw new IllegalArgumentException("Backing map cannot be null.");@b@ }@b@ this.name = name;@b@ this.map = backingMap;@b@ }@b@@b@ public V get(K key) throws CacheException {@b@ return map.get(key);@b@ }@b@@b@ public V put(K key, V value) throws CacheException {@b@ return map.put(key, value);@b@ }@b@@b@ public V remove(K key) throws CacheException {@b@ return map.remove(key);@b@ }@b@@b@ public void clear() throws CacheException {@b@ map.clear();@b@ }@b@@b@ public int size() {@b@ return map.size();@b@ }@b@@b@ public Set<K> keys() {@b@ Set<K> keys = map.keySet();@b@ if (!keys.isEmpty()) {@b@ return Collections.unmodifiableSet(keys);@b@ }@b@ return Collections.emptySet();@b@ }@b@@b@ public Collection<V> values() {@b@ Collection<V> values = map.values();@b@ if (!map.isEmpty()) {@b@ return Collections.unmodifiableCollection(values);@b@ }@b@ return Collections.emptySet();@b@ }@b@@b@ public String toString() {@b@ return new StringBuilder("MapCache '")@b@ .append(name).append("' (")@b@ .append(map.size())@b@ .append(" entries)")@b@ .toString();@b@ }@b@}
3.AbstractCacheManager、MemoryConstrainedCacheManager实现类(CacheManager接口)
package org.apache.shiro.cache;@b@@b@import org.apache.shiro.util.Destroyable;@b@import org.apache.shiro.util.LifecycleUtils;@b@import org.apache.shiro.util.StringUtils; @b@import java.util.Collection;@b@import java.util.concurrent.ConcurrentHashMap;@b@import java.util.concurrent.ConcurrentMap;