标签:
public class RoleMenuCache implements IClearCache { private static Map<String, RoleMenu> roleMenuCache = new HashMap<String, RoleMenu>(); ...业务代码省略 }
这里主要是替换这个HashMap所以改动就比较小。
public class CacheManager { private final static Logger logger = LoggerFactory.getLogger(CacheManager.class); private static Map<String, ICache> caches = new ConcurrentHashMap<>(); private static ICacheStrategy cacheStrategy = new DefaultCacheStategy(); private static String cacheStrategyClass; @SuppressWarnings("unchecked") public static synchronized <T extends ICache> T getOrCreateCache(String cacheName, Class<?> keyClass, Class<?> valueCalss) { T cache = (T) caches.get(cacheName); if (cache != null) { return cache; } cache = (T) cacheStrategy.createCache(cacheName, keyClass, valueCalss); caches.put(cacheName, cache); return cache; } @SuppressWarnings("rawtypes") public static synchronized void destroyCache(String cacheName) { ICache cache = caches.remove(cacheName); if (cache != null) { cache.clear(); } } }
public interface ICacheStrategy { ICache createCache(String name, Class<?> keyClass, Class<?> valueCalss); void destroyCache(ICache cache); }
public class DefaultCache<K, V> implements ICache<K, V> { protected Map<K, V> map; private String name; private long maxCacheSize; private long maxLifetime; private int cacheSize = 0; public DefaultCache(String name, long maxSize, long maxLifetime) { this.name = name; this.maxCacheSize = maxSize; this.maxLifetime = maxLifetime; map = new ConcurrentHashMap<K, V>(103); } @Override public V get(Object key) { return map.get(key); } @Override public V put(K key, V value) { return map.put(key, value); } @Override public V remove(Object key) { return map.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) { map.putAll(m); } @Override public void clear() { if (map != null) { map.clear(); } } }
对于调用方来说其实就很简单,只需要调用CacheManager即可,还是前面举的RoleMenuCache
public class RoleMenuCache implements IClearCache { private static Map<String, RoleMenu> roleMenuCache; static { roleMenuCache = CacheManager.getOrCreateCache("permissionCache", String.class, RoleMenu.class); } ...业务代码省略 }
对于老代码的改造还是比较小的,而且这样的好处是以后想换成redis的也很简单,对于业务代码就不需要再修改了。
/** * 根据key设置map的值 */ @Override public V put(K key, V value) { jedisTemp.hset(name, JSON.toJSONString(key), JSON.toJSONString(value)); return value; }
这并没啥问题,因为对象转换成json串是正常的。问题是get的时候,我们使用的
CacheManager.getOrCreateCache("permissionCache", String.class, RoleMenu.class);
最终get方法的实现就是这样:
@Override public V get(Object key) { String json = jedisTemp.hget(name, JSON.toJSONString(key)); return (V) JSON.parseObject(json, valueClass); }
问题虽然是解决了,只不过总觉得怪怪的。
标签:
原文地址:http://www.cnblogs.com/5207/p/5788439.html