代码层缓存的使用

  1. oscache.properties 配置:

     cache.memory=true
    cache.capacity=1000
    cache.key=__oscache_cache
    cache.blocking=false
    cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache
    cache.persistence.overflow.only=true

  2. 引入oscache-2.1.jar

  3. 编写类

  4. import com.opensymphony.oscache.base.NeedsRefreshException;
    import com.opensymphony.oscache.general.GeneralCacheAdministrator;
    /**
     * @className:OSCacheImp.java
     * @classDescription:
     */

  5. public class OSCacheManage {
     private static OSCacheManage myCacheManage;

  6.  private static GeneralCacheAdministrator cache;

  7.  /**
      * 初始化缓存管理容器
      */
     static void init() {
      try {
       if (cache == null)
        cache = new GeneralCacheAdministrator();
      } catch (Exception e) {
       e.printStackTrace();

  8.   }
     }

  9.  /**
      * 获取CacheManager对象(饿汉单例模式)
      *
      * @return
      */
     public static OSCacheManage getInstance() {
      if (myCacheManage == null) {
       myCacheManage = new OSCacheManage();
       init();
      }
      return myCacheManage;

  10.  }

  11.  /**
      * 设置Cache
      *
      * @param  key
      * @param  value
      */
     public void setCache(String key, Object value) {
      cache.putInCache(key, value);
     }

  12.  /**
      * 获取cache
      *
      * @param key
      *            关键字
      * @return
      */
     public Object getCache(String key) {
      Object object = null;
      try {
       object = cache.getFromCache(key);
      } catch (NeedsRefreshException e) {
       cache.cancelUpdate(key);
      }
      return object;
     }
     
     /**
      * 获取cache并清除cache
      */
     public Object getCacheAndFlush(String key) {
      Object object = null;
      try {
       object = cache.getFromCache(key,1);
      } catch (NeedsRefreshException e) {
       cache.cancelUpdate(key);
      }
      return object;
     }
     
     /**
      * 根据key值清除缓存
      *
      * @param key
      *            关键字
      */
     public void clearCache(String key) {
      cache.flushEntry(key);
     }

  13.  /**
      * 清除所有缓存
      *
      * @param key
      *            关键字
      */
     public void clearAllCache() {
      cache.flushAll();
     }

  14.  /**
      * 根据日期清除缓存对象
      */
     public void removeAll(Date date) {
      cache.flushAll(date);
     }
    }

转载于:https://my.oschina.net/u/817550/blog/365238

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值