您的位置:首页 > 其它

用Map实现简单缓存

2016-07-06 16:30 309 查看


import java.util.Iterator;

import java.util.Map;

import java.util.Set;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

/**

 * 缓存池

 * @author **

 * @date 2016年7月6日 下午3:22:54

 */

public class CachePool {

 private static final Logger logger = LogManager.getLogger(CachePool.class);

 

 private static CachePool cachePool;

 private Map<Object, Object> cacheItems;

 

 private CachePool() {

  cacheItems = new ConcurrentHashMap<Object, Object>();

 }

 

 @Autowired

 private ISearchMerchantService searchMerchantService;

 

 /**

  * 获取唯一实例

  * @return

  */

 public static CachePool getInstance() {

  if (cachePool == null) {

   synchronized (CachePool.class) {

    if(cachePool == null) {

     cachePool = new CachePool();

    }

   }

  }

  return cachePool;

 }

 

 /**

  * 清空cache

  */

 public void clearAllIterms() {

  cacheItems.clear();

 }

 

 /**

  * 刷新cache

  */

 public void refresh () {

  logger.info("Before refreshing Cache size = {}", cachePool.getSize() );

  //清空缓存

  cacheItems.clear();

  //重新查库

  /*Map<String, String> merchantMap = searchMerchantService.searchMerchants();

  //遍历map

  Set<String> set = merchantMap.keySet();

  Iterator<String> it = set.iterator();

  while(it.hasNext()) {

   Object key = it.hasNext();

   Object value = merchantMap.get(key);

   if(key != null && value != null) {

    cachePool.putCacheItem(key.toString(), value.toString());

   }

  }*/

  

  logger.info("After the refresh Cache size = {}", cachePool.getSize() );

 }

 

 /**

  * 获取指定cache信息

  * @param key

  * @return

  */

 public Object getCacheItem(Object key) {

  if(cacheItems.containsKey(key)) {

   return cacheItems.get(key);

  }

  return null;

 }

 

 /**

  * 存放cache信息

  * @param key

  * @param value

  */

 public void putCacheItem(Object key, Object value) {

  if(!cacheItems.containsKey(key)) {

   cacheItems.put(key, value);

  }

 }

 

 /**

  * 获取cache长度

  * @return

  */

 public int getSize() {

  return cacheItems.size();

 }

 public Map<Object, Object> getCacheItems() {

  return cacheItems;

 }

 public void setCacheItems(Map<Object, Object> cacheItems) {

  this.cacheItems = cacheItems;

 }

 

 

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Map 缓存