java中的缓存功能

      当你频繁对数据库进行操作时,很有可能导致数据库连接数量过多,报连接过多的错误,严重情况下将会导致数据库的崩溃。

java中的缓存就是用来解决这个问题

      当你需要完成一个缓存模块时,1、首先需要创建一个缓存的实体类(其中包含属性有:保存的数据,保存的时间,最后刷新的时间)

2、其次再定义缓存操作的接口(接口中包含方法有:数据的存入,单个数据的取出以及多个数据的存取,是根据名称进行存取,判断缓存是否存在、判断缓存是否失效、删除缓存等等的方法)

3、创建实现缓存的操作接口类,实现接口中定义的方法后对方法进行逻辑处理

4、创建缓存的监听类,运用线程对缓存数据进行监听,及时删除失效的缓存以解放空间

5、在你需要进行缓存的地方,调用实现类中的方法,传递需要的参数,进行缓存的存取

       这里开始上代码:

1、缓存实体类对象

package cache;

/**
 * @author mzy
 * 缓存的实体对象
 */
public class EntityCache {
  /**
   * 保存的数据
   */
  private  Object datas;

  /**
   * 设置数据失效时间,为0表示永不失效
   */
  private  long timeOut;

  /**
   * 最后刷新时间
   */
  private  long lastRefeshTime;

  public EntityCache(Object datas, long timeOut, long lastRefeshTime) {
    this.datas = datas;
    this.timeOut = timeOut;
    this.lastRefeshTime = lastRefeshTime;
  }
  public Object getDatas() {
    return datas;
  }
  public void setDatas(Object datas) {
    this.datas = datas;
  }
  public long getTimeOut() {
    return timeOut;
  }
  public void setTimeOut(long timeOut) {
    this.timeOut = timeOut;
  }
  public long getLastRefeshTime() {
    return lastRefeshTime;
  }
  public void setLastRefeshTime(long lastRefeshTime) {
    this.lastRefeshTime = lastRefeshTime;
  }


}

2、定义缓存的操作接口

public interface ICacheManager {
    /**
     * 存入缓存
     * @param key
     * @param cache
     */
    void putCache(String key, EntityCache cache);
    
    /**
     * 存入缓存
     * @param key
     * @param cache
     */
    void putCache(String key, Object datas, long timeOut);
    
    /**
     * 获取对应缓存
     * @param key
     * @return
     */
    EntityCache getCacheByKey(String key);
    
    /**
     * 获取对应缓存
     * @param key
     * @return
     */
    Object getCacheDataByKey(String key);
    
    /**
     * 获取所有缓存
     * @param key
     * @return
     */
    Map<String, EntityCache> getCacheAll();
    
    /**
     * 判断是否在缓存中
     * @param key
     * @return
     */
    boolean isContains(String key);
    
    /**
     * 清除所有缓存
     */
    void clearAll();
    
    /**
     * 清除对应缓存
     * @param key
     */
    void clearByKey(String key);
    
    /**
     * 缓存是否超时失效
     * @param key
     * @return
     */
    boolean isTimeOut(String key);
    
    /**
     * 获取所有key
     * @return
     */
    Set<String> getAllKeys();
}

3、创建实现缓存的操作类接口

public class CacheManagerImpl implements ICacheManager {
    private static Map<String, EntityCache> caches = new ConcurrentHashMap<String, EntityCache>();

    /**
     * 存入缓存
     * @param key
     * @param cache
     */
    public void putCache(String key, EntityCache cache) {
        caches.put(key, cache);
    }
    
    /**
     * 存入缓存
     * @param key
     * @param cache
     */
    public void putCache(String key, Object datas, long timeOut) {
        timeOut = timeOut > 0 ? timeOut : 0L;
        putCache(key, new EntityCache(datas, timeOut, System.currentTimeMillis()));
    }
    
    /**
     * 获取对应缓存
     * @param key
     * @return
     */
    public EntityCache getCacheByKey(String key) {
        if (this.isContains(key)) {
            return caches.get(key);
        }
        return null;
    }
    
    /**
     * 获取对应缓存
     * @param key
     * @return
     */
    public Object getCacheDataByKey(String key) {
        if (this.isContains(key)) {
            return caches.get(key).getDatas();
        }
        return null;
    }

    /**
     * 获取所有缓存
     * @param key
     * @return
     */
    public Map<String, EntityCache> getCacheAll() {
        return caches;
    }
    
    /**
     * 判断是否在缓存中
     * @param key
     * @return
     */
    public boolean isContains(String key) {
        return caches.containsKey(key);
    }

    /**
     * 清除所有缓存
     */
    public void clearAll() {
        caches.clear();
    }
    
    /**
     * 清除对应缓存
     * @param key
     */
    public void clearByKey(String key) {
        if (this.isContains(key)) {
            caches.remove(key);
        }
    }
    
    /**
     * 缓存是否超时失效
     * @param key
     * @return
     */
    public boolean isTimeOut(String key) {
        if (!caches.containsKey(key)) {
            return true;
        }
        EntityCache cache = caches.get(key);
        long timeOut = cache.getTimeOut();
        long lastRefreshTime = cache.getLastRefeshTime();
        if (timeOut == 0 || System.currentTimeMillis() - lastRefreshTime >= timeOut) {
            return true;
        }
        return false;
    }

    /**
     * 获取所有key
     * @return
     */
    public Set<String>  getAllKeys() {
        return caches.keySet();
    }
}

4、创建缓存的监听类

public class CacheListener{
    Logger logger = Logger.getLogger("cacheLog");
    private CacheManagerImpl cacheManagerImpl;
    public CacheListener(CacheManagerImpl cacheManagerImpl) {
        this.cacheManagerImpl = cacheManagerImpl;
    }
    
    public void startListen() {
        new Thread(){
            public void run() {
                while (true) {
                    for(String key : cacheManagerImpl.getAllKeys()) {
                        if (cacheManagerImpl.isTimeOut(key)) {
                         cacheManagerImpl.clearByKey(key);
                         logger.info(key + "缓存被清除");
                     }
                    } 
                }
            }  
        }.start();
    }
}

5、在需要的地方进行缓存的存取使用

6、我项目中更改了监听类,因为我不需要失效时间,我这里只需要一直存入缓存,几秒后删除缓存。

这里是让监听类中的缓存进行睡眠,睡够一定时间之后进行缓存的清空

public class CacheListener{
  Logger LOG = Logger.getLogger(CacheListener.class);
  private CacheManagerImpl cacheManagerImpl;
  public CacheListener(CacheManagerImpl cacheManagerImpl) {
    this.cacheManagerImpl = cacheManagerImpl;
  }

  public void startListen() {
      new Thread(){
        public void run() {
          if(cacheManagerImpl.isContains("list")){
              try {
                TimeUnit.SECONDS.sleep(10);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              List<DcMessages> m = cacheManagerImpl.getCacheDataByKey("list");
              GetStatusThread thread = new GetStatusThread(m);
              thread.run();
              cacheManagerImpl.clearByKey("list");
            }else{
            return;
          }
        }
      }.start();
    }
  }

到这里,整个缓存功能就可以实现了,欢迎大家进行问题的指点

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值