All Downloads are FREE. Search and download functionalities are using the official Maven repository.

yui.comn.mybatisx.extension.cache.RamCache Maven / Gradle / Ivy

/**
 * Project: mybatis-link-core
 * Class RamCache
 * Version 1.0
 * File Created at 2021-4-20
 * $Id$
 * author yuyi
 * email [email protected]
 */
package yui.comn.mybatisx.extension.cache;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import lombok.extern.slf4j.Slf4j;

/**
 * 

* 内存缓存 *

* * @author yuyi ([email protected]) */ @Slf4j public class RamCache extends AbstractCache { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); /** * 一个id对应的所有缓存key */ private static Map> ID_KEY_MAP = new HashMap<>(); /** * 缓存 */ private static Map CACHE_MAP; // = new ConcurrentHashMap<>(); private static String eldestKey; private static int MAX_SIZE = 10240; static { CACHE_MAP = new LinkedHashMap(MAX_SIZE, .75F, true) { private static final long serialVersionUID = 4267176411845948333L; @Override protected boolean removeEldestEntry(Map.Entry eldest) { boolean tooBig = size() > MAX_SIZE; if (tooBig) { eldestKey = eldest.getKey(); } return tooBig; } }; } public RamCache(String id) { super(id); } @Override public void putObject(Object key, Object value) { if (null != value) { try { CACHE_MAP.put(getKey(key), value); addIdKey(key); cycleKeyList(); } catch (Exception e) { log.error("putObject error", e); } } } @Override public Object getObject(Object key) { try { if (null != key) { return CACHE_MAP.get(getKey(key)); } } catch (Exception e) { log.error("缓存出错 ", e); } return null; } @Override public Object removeObject(Object key) { if (null != key) { try { CACHE_MAP.remove(getKey(key)); delIdKey(key); } catch (Exception e) { log.error("removeObject error", e); } } return null; } @Override public int getSize() { try { return CACHE_MAP.size(); } catch (Exception e) { log.error("getSize error", e); } return 0; } @Override protected void clear(String id) { log.debug("清空缓存"); try { Set keys = ID_KEY_MAP.get(id); if (null != keys) { for (String key : keys) { CACHE_MAP.remove(key); } } ID_KEY_MAP.remove(id); } catch (Exception e) { log.error("clear error", e); } } @Override public ReadWriteLock getReadWriteLock() { return this.readWriteLock; } private void addIdKey(Object key) { Set keys = ID_KEY_MAP.get(id); if (null == keys) { keys = new HashSet<>(); ID_KEY_MAP.put(id, keys); } keys.add(getKey(key)); } private void delIdKey(Object key) { Set keys = ID_KEY_MAP.get(id); if (null != keys) { keys.remove(getKey(key)); } } private void cycleKeyList() { if (eldestKey != null) { CACHE_MAP.remove(eldestKey); eldestKey = null; } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy